Array slice(): copy a range
Quick answer
Slice returns a new array containing a selected range without modifying the source array. Its end position is excluded.
How it works
items.slice(start, end) selects from start through the position before end. Negative indices count back from length; omitted end means the end of the array. The copy is shallow: object elements are not recursively copied.
const a = [10, 20, 30, 40];const b = a.slice(1, 3);console.log(b[0], b[1], a.length);Expected output in Node.js:
20 30 4Indices one and two are selected; the original keeps four items.
const a = [1, 2, 3, 4];const tail = a.slice(-2);tail[0] = 9;console.log(a[2], tail[0]);Expected output in Node.js:
3 9The new array has independent indexed slots.
Common mistakes
Do not confuse slice with splice. The latter mutates the receiver and its second argument is a count.
Practice
Extract the last two entries from arrays of lengths zero, one and four.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array slice(): copy a range — Knowledge Check
Apply the taught concept and reason about the result.
What is [1,2,3,4].slice(1,3)?
What is [1,2,3].slice(-1)?
Does slice mutate its ordinary source array?
If a sliced element is an object, what is copied into the new array?
What is [1,2].slice(2,1)?