JavaScript Reference ยท Array
Array.prototype.slice()
Reference for JavaScript Array.prototype.slice(): copy a portion of an array with start and end indexes, negative values, shallow copies and the slice/splice mix-up.
The slice() method returns a new array holding a portion of the original, from a start index up to, but not including, an end index. The original array is never changed.
Called with no arguments, it makes a shallow copy of the whole array. Do not confuse it with splice(), which changes the array in place.
const letters = ["a", "b", "c", "d", "e"]; letters.slice(1, 3); // ["b", "c"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.slice() array.slice(start) array.slice(start, end)
| Name | Description |
|---|---|
start |
Optional. Index where the copy begins. Negative values count from the end. Defaults to 0. |
end |
Optional. Index where the copy stops; that element is not included. Negative values count from the end. Defaults to array.length. |
Return value: a new array with the copied elements. It is empty if start is at or past end.
Exceptions: none for ordinary arrays.
Usage notes
- Non-mutating.
slice()never changes the original;splice()does.- Shallow copy. Elements are copied by value for primitives and by reference for objects, so changing an object through the copy changes it in the original. UsestructuredClone()for a deep copy. - Out-of-range values are clamped. A
startpast the end gives[]; anendbeyond the length means "to the end"; very negative values mean0. - Fractions are truncated, and
NaNbecomes0. - Copy idioms:
array.slice(),[...array]andArray.from(array)all make a shallow copy. - Last items:
array.slice(-3)returns the last three elements (or all of them if there are fewer). - Without the last item:
array.slice(0, -1). - Holes in sparse arrays are preserved in the result.
- Array-likes and strings.
Array.prototype.slice.call(arrayLike)converts an array-like to a real array;Array.from()is the modern way. Strings and typed arrays have their ownslice().
Browser support
Array.prototype.slice() is part of ES3 and works everywhere.