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

← All JS array methods · TypeScript vs JavaScript