QUESTION 20 / 20 · ARRAYS · INTERMEDIATE

Where a slice ends

What will this code print? Read each line, then make your prediction.

Where this matters

Slice is useful for displaying a portion of a list while preserving the original list. Its second argument is an exclusive index, not a count.

JavaScript · read-only example
const values = [1, 2, 3];
console.log(JSON.stringify(values.slice(0, 2)));
console.log(JSON.stringify(values));
Your prediction

Read the full explanation

Slice includes index zero and excludes index two. It returns a shallow copy without removing elements from the input.

Trace the code

  1. Index 0 contains 1 and index 1 contains 2.
  2. Index 2 is the stopping boundary and is not included.
  3. The new array contains the selected entries; the source array keeps all three. Nested objects would still be shared.

Why the other predictions differ

  • [1,2,3] [1,2,3] — The ending index is excluded.
  • [1,2] [3] — Slice does not mutate; splice is a different method.
Expected console output
[1,2]
[1,2,3]

Reading this explanation does not record mastery. A correct submitted attempt can do so, including after review.

Change one thing

Move the starting index to 1 and leave the end at 2.

Predict the result, then run this self-contained snippet in your browser’s developer console. It uses only sample values and makes no network requests.

console.log(JSON.stringify([1, 2, 3].slice(1, 2)));
Check the variation’s output
[2]

Explain which binding, value, or operation changed before moving to the next challenge.