Array.prototype.slice
Returns part of an array.
Available since: ES3
Syntax
array.slice(start, end)Parameters
| Parameter | Type | Description |
|---|---|---|
| start | number | The index to start from. A negative value counts from the end. |
| end | number | Optional. The index to stop before. Defaults to the end of the array. |
Return value
ArrayA new array with the selected elements.
Examples
Elements at indexes 1, 2 and 3:
console.log([1, 2, 3, 4, 5].slice(1, 4).join(', '));Output:
2, 3, 4The last two elements:
console.log([1, 2, 3, 4, 5].slice(-2).join(', '));Output:
4, 5Notes
The source array is not modified. Do not confuse it with splice(), which removes elements from the array itself.
See also
- Array.prototype.push — Appends elements to the end of an array.
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.splice — Removes, replaces or inserts elements in the middle of an array.
- Array.prototype.at — Returns the element at an index; negative indexes are allowed.
Related recipes
In the tutorial
- Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.