Array.prototype.slice()
Returns a shallow copy of a portion of an array into a new array.
Syntax
arr.slice(start, end) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
start | number | No | Zero-based index to begin extraction. Negative counts from the end. Defaults to 0. |
end | number | No | Zero-based index before which to stop (exclusive). Negative counts from the end. Defaults to array length. |
Returns
Array — A new array containing the extracted elements.
Examples
const a = [1, 2, 3, 4, 5];
console.log(a.slice(1, 3));
Output
[ 2, 3 ]
console.log([1, 2, 3, 4].slice(-2));
Output
[ 3, 4 ]
Notes
Does not mutate the original array (unlike `splice`). Performs a shallow copy,
so nested objects are shared by reference. Call with no arguments to clone an array.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |