The JavaScript array.slice() method
The slice() method copies a section of an array into a new array, from a start index up to (but not including) an end index. [1, 2, 3, 4].slice(1, 3) returns [2, 3]. It never changes the original — which is the big difference from the similarly named splice().
Overview
slice() gives you a copy of part of an array. You pass a start index and an end index, and you get back a new array containing the elements in between — including the start, but not the end. So slice(1, 3) gives you indexes 1 and 2. Leave out the end and it copies to the end of the array; leave out both and you get a shallow copy of the whole thing, which is a handy trick.
Both arguments can be negative, in which case they count from the end: slice(-2) returns the last two elements. Because it never touches the original array, slice() is the safe, non-destructive way to grab a portion — paginating results, taking the top few, copying before sorting.
The name is one letter away from splice(), and that's the trap. slice() copies and returns; splice() cuts the original apart and mutates it. If you don't want to change the source array, you want slice(). Note the copy is shallow, so nested objects are shared by reference, not cloned.
Syntax
const newArray = array.slice() // shallow copy of the whole array
const newArray = array.slice(start) // from start to the end
const newArray = array.slice(start, end) // from start up to (not including) end
Parameters
The array.slice() method accepts the following parameters.
| Parameter | Description |
|---|---|
start |
Optional. Index to start copying from. Negative counts from the end. Defaults to 0. |
end |
Optional. Index to stop before (not included). Negative counts from the end. Defaults to the array's length. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const letters = ['a', 'b', 'c', 'd', 'e'];
document.getElementById('out').textContent =
'slice(1, 3): ' + letters.slice(1, 3).join(', ') + '\n' +
'slice(-2): ' + letters.slice(-2).join(', ') + '\n' +
'original: ' + letters.join(', '); // unchanged
</script>
Best practices
- Reach for
slice()when you must not change the original array — it always returns a fresh one. - Remember
endis exclusive:slice(0, 2)returns two elements, indexes 0 and 1. - Use negative indices for "from the end" —
slice(-3)is the last three elements. - Don't confuse it with splice(), which mutates. Same spelling, opposite behavior.
Frequently asked questions
What is the difference between slice() and splice()?
slice() returns a copy of part of the array and leaves the original alone; splice() changes the original by removing or inserting elements. Slice copies, splice mutates.Does slice() change the original array?
How do I copy an array with slice()?
const copy = arr.slice(). It's a shallow copy, so nested objects are still shared.How do I get the last few elements of an array?
arr.slice(-3) returns the last three elements.