JavaScript Slice
slice() extracts a portion of an array between a start and an end index and returns it as a new array. The end index is exclusive and negative indexes count from the end. The original array is never modified.
Syntax
arr.slice(1, 3) Examples
| Input | Arguments | Output |
|---|---|---|
| [1, 2, 3, 4] | 1, 3 | [2, 3] |
| [1, 2, 3, 4] | -2, 4 | [3, 4] |
| ↳ A negative index counts from the end. | ||
When to use it
- Take the first N items of a list (pagination, top 3).
- Copy an array before a mutating operation.
Gotchas
- end is exclusive: slice(1, 3) returns the elements at indexes 1 and 2.
- Not to be confused with splice(), which mutates the array.
Try it live
Type your input and see Slice transform it instantly.
Want to go further? Chain Slice with other functions, pipe one output into the next and watch your data transform in the visual Playground.