Array.prototype.slice()

Returns a shallow copy of a portion of an array selected by start and end indices, leaving the original intact.

Signature
slice()
slice(start)
slice(start, end)
  • Added in JavaScript ES3

Parameters

ParameterTypeDescription
$startoptionalnumber= 0Zero-based index at which to start extraction, converted to an integer. A negative index counts back from the end. If start < -array.length or start is omitted, 0 is used. If start >= array.length, an empty array is returned.
$endoptionalnumber= array.lengthZero-based index at which to end extraction, converted to an integer; extraction stops before end. A negative index counts back from the end. If end >= array.length or end is omitted or undefined, array.length is used.

Return value

ArrayA new array containing the extracted elements.

Errors

Nothing under normal use; slice() is generic and works on any array-like this value.

Changelog

  • PHP ES3Introduced on Array.prototype.
  • PHP ES2015Species constructor support: subclasses of Array return an instance of the subclass.

slice() extracts a section of an array into a new array. It never touches the original, which is the single most important thing to remember about it — and the reason it is so easy to confuse with splice(), whose name differs by one letter and which does the opposite.

When to reach for it

Use it to take a window of data (page 2 of a result set), to grab the first or last n items, or — with no arguments at all — to make a quick copy of an array before running a mutating method like sort() or reverse() on it. Negative indices make "the last three" a one-liner: arr.slice(-3).

What trips people up

The end index is exclusive, so slice(1, 3) gives you two elements, not three. Passing a start at or past the end returns an empty array rather than throwing, which can silently swallow off-by-one errors.

The copy is shallow. Objects in the new array are the same objects as in the old one, so mutating copy[0].id changes the original too. Use a structured clone or a manual deep copy when that matters.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Paginate a result set by taking a fixed-size window of rows
  • Copy an array before calling sort() or reverse() so the source stays ordered
  • Take the last N entries of a log or history buffer with a negative start
  • Convert an array-like arguments or NodeList into a real array

Frequently asked questions

What is the difference between slice() and splice()?

slice() returns a new array and leaves the original untouched, while splice() removes or inserts elements in the original array and returns only what it removed.

How do I get the last N elements of an array?

Call arr.slice(-n), where a negative start counts back from the end; arr.slice(-3) returns the final three elements and returns the whole array if it is shorter than three.

Does slice() deep copy nested objects?

No, it makes a shallow copy: the new array holds the same object references, so mutating a nested object through the copy is visible in the original.

More examples

Paginating a list

Page 3 returns only the three remaining rows because slice() clamps end to the array length. Asking for a page beyond the data yields an empty array instead of throwing.

Example · javascript
const rows = Array.from({ length: 23 }, (_, i) => `row-${i + 1}`);
const pageSize = 10;

function page(n) {
  return rows.slice((n - 1) * pageSize, n * pageSize);
}

console.log(page(1).length); // 10
console.log(page(3));        // ['row-21','row-22','row-23']
console.log(page(9));        // [] — past the end, no error

Copying before a mutating sort

The first sort operates on a copy, so prices keeps its insertion order. The second call shows what happens without the copy: sort() rewrites the source array and returns the same reference.

Example · javascript
const prices = [30, 10, 20];

const sorted = prices.slice().sort((a, b) => a - b);
console.log(sorted); // [10,20,30]
console.log(prices); // [30,10,20] — original order preserved

const wrong = prices.sort((a, b) => a - b);
console.log(prices); // [10,20,30] — sort() mutated in place
console.log(wrong === prices); // true

Turning an array-like into an array

slice() is generic: given any object with a length and integer keys it produces a real array. The final lines show that holes survive the copy rather than becoming undefined.

Example · javascript
const arrayLike = { length: 3, 0: "x", 1: "y", 2: "z" };

const real = Array.prototype.slice.call(arrayLike);
console.log(real);            // ['x','y','z']
console.log(Array.isArray(real)); // true

// slice() preserves empty slots.
const sparse = [1, , 3];
console.log(1 in sparse.slice()); // false — still a hole

Discussion

  • Be the first to comment on this lesson.