#42: slice then splice on the same array
Topic: arrays · Difficulty: ★★
const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 3);
const spliced = arr.splice(1, 3);
console.log(sliced);
console.log(spliced);
console.log(arr);Output
[ 2, 3 ] [ 2, 3, 4 ] [ 1, 5 ]
Why
slice(1, 3) is non-mutating: it returns a shallow copy of the elements from index 1 up to (not including) index 3 — [2, 3] — and leaves the original array completely untouched. splice(1, 3), called afterward on the still-intact original, is mutating: it removes 3 elements starting at index 1 ([2, 3, 4]) and returns those removed elements, while permanently altering arr in place to [1, 5]. The similar names and the fact that both accept a start index trip up developers who expect slice's read-only behavior from splice, or vice versa.