What does slice() do in JavaScript?
Short answer: array.slice(start, end) returns a new array with the items from start up to end, without including end. The original array doesn't change. Negative numbers count from the end, so slice(-2) gives the last two items.
const fruits = ["apple", "banana", "cherry", "kiwi"];
fruits.slice(1, 3); // ["banana", "cherry"]
fruits.slice(-2); // ["cherry", "kiwi"]
console.log(fruits); // ["apple", "banana", "cherry", "kiwi"] unchangedDon't confuse it with splice(), which removes items from the original array.
slice() copies a range without the end position, counts from the end with negative numbers and never changes the original array.
slice() at a glance
| What you want | Code | Result |
|---|---|---|
| From position 1 to 3 (3 not included) | fruits.slice(1, 3) | ["banana", "cherry"] |
| From position 2 to the end | fruits.slice(2) | ["cherry", "kiwi"] |
| The last 2 items | fruits.slice(-2) | ["cherry", "kiwi"] |
| Everything except the last | fruits.slice(0, -1) | ["apple", "banana", "cherry"] |
| The first 3 items | fruits.slice(0, 3) | ["apple", "banana", "cherry"] |
| A copy of the whole array | fruits.slice() | A new array with the same items |
| Page 2 of 3 items per page | items.slice(3, 6) | Items 4 to 6 |
| Part of a string | "hello world".slice(0, 5) | "hello" |
Syntax of slice()
array.slice()
array.slice(start)
array.slice(start, end)start(optional): the first position to copy. By default0.end(optional): where to stop. This position is not included. By default, the end of the array.
Both accept negative numbers: -1 is the last position, -2 the one before it. If start is greater than end, or beyond the length, you get an empty array: fruits.slice(3, 1) is [].
