Array.prototype.slice()
The non-mutating twin of splice, and one letter away from it. slice COPIES a range out; splice CUTS one out. Confusing them is the single most common Array mistake after sort.
Demo
slice(1, 3) gives you elements 1 and 2 — the element at index 3 is excluded, which is why the result has exactly end minus start elements. A negative start counts from the back, so -2 takes the last two. The two degenerate cases return empty rather than erroring: start equal to end selects nothing, and an end BEFORE the start also gives an empty array instead of reversing. An end past the array simply stops at the end.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| start | number | no (0) | Index to start at. Negative counts from the end, so -2 means "two from the back". Beyond the length gives an empty array. |
| end | number | no (length) | Index to stop BEFORE — the element at this index is not included. Negative counts from the end. |
Return value
Array — A NEW array holding elements from start up to but NOT including end. The original is never modified.
Common patterns
const copy = items.slice(); const copy2 = [...items];
const sorted = items.slice().sort((a, b) => a - b);
const lastThree = items.slice(-3);
Examples
Pitfalls
const a = [1, 2, 3]; const b = a.splice(0, 2); a
const a = [1, 2, 3]; const b = a.slice(0, 2); a
[1, 2, 3, 4].slice(0, 2)
[1, 2, 3, 4].slice(0, 3)
const a = [{n: 1}]; const b = a.slice(); b[0].n = 99; a[0].n
const b = structuredClone(a);
[1, 2, 3, 4].slice(3, 1)
[1, 2, 3, 4].slice(Math.min(a, b), Math.max(a, b))
When to use
- Copying part of an array without touching the original
- Shallow-copying a whole array
- Taking the first or last N elements
- Guarding an array before a mutating method like sort
- You want to REMOVE elements → splice, or filter for a copy
- You need independent nested objects → structuredClone
- Selecting by a test rather than by position → filter
Notes
FAQ
slice copies a range into a new array and leaves the original alone. splice removes (and optionally inserts) elements IN the original, and returns the removed ones. One letter, opposite effects on your data.
const a = [1, 2, 3]; a.slice(0, 2); // [1, 2], a unchanged a.splice(0, 2); // [1, 2], a is now [3]