inspection
Array.prototype.slice
Returns a shallow copy of a portion of the array from start (inclusive) to end (exclusive) without modifying the source. Reach for it to extract a range or to clone an array (`arr.slice()`).
arr.slice([start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| start | Index to begin extraction (default 0); negative counts from the end |
| end | Index to stop before (default arr.length); negative counts from the end |
Examples
console.log([1,2,3,4,5].slice(1, 3)); Logs: [2, 3]
console.log([1,2,3,4,5].slice(-2)); Logs: [4, 5]
const a = [1,2,3]; const b = a.slice(); console.log(a === b, b); Logs: false [1, 2, 3] (slice() shallow-clones)
console.log([1,2,3].slice(0, -1)); Logs: [1, 2] (drop the last item)
Gotcha
Non-mutating (unlike splice) and returns a SHALLOW copy — nested objects/arrays are shared with the original. Don't confuse `slice` with `splice`.
Related methods
Array.prototype.splice
Removes and/or inserts elements at any position in the array, returning the removed items. Reach for it to do insert/delete/replace edits in one call.
Array.prototype.concat
Returns a new array formed by joining the source with the provided arrays and/or values (one level of spread). Reach for it to merge arrays without mutating any of them.
Array.prototype.at
Returns the element at the given integer index, supporting negative values that count from the end (ES2022). Reach for it as the clean replacement for `arr[arr.length - 1]`.
Array.prototype.join
Returns a string formed by concatenating each element, separated by the given string (default ','). Reach for it to build CSV/URL/paths or any delimited string from an array.