Lesson 14 / 38

Array Methods: push, pop, slice, splice

Adding, removing, and copying parts of an array.

Adding & removing

push/pop work at the end, unshift/shift at the start — all four mutate the original array.

const nums = [1, 2, 3];
nums.push(4);       // [1, 2, 3, 4]
nums.pop();          // removes 4 -> [1, 2, 3]
nums.unshift(0);     // [0, 1, 2, 3]
nums.shift();        // removes 0 -> [1, 2, 3]

slice vs splice

slice copies a range without mutating; splice mutates the original array in place.

const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 3));   // [2, 3], arr unchanged
arr.splice(1, 2, "a", "b");     // remove 2, insert 2
console.log(arr);               // [1, 'a', 'b', 4, 5]

Mutating vs non-mutating

push, pop, splice, sort, reverse mutate. slice, concat, map, filter return a new array — know which is which.