SyntaxStudy
Sign Up
JavaScript Beginner 7 min read

Mutating Array Methods

Mutating Array Methods

Some array methods modify the original array in place — they are called mutating methods. Knowing which methods mutate and which do not is critical for avoiding subtle bugs, especially in frameworks like React where state immutability matters.

push and pop

push(...items) appends items to the end and returns the new length. pop() removes and returns the last item. Both operate in O(1) time.

shift and unshift

shift() removes the first element (returns it). unshift(...items) adds items to the beginning. Both are O(n) because all remaining elements must be re-indexed.

splice(start, deleteCount, ...items)

splice is the Swiss army knife of array mutation — it can remove, replace, and insert elements at any position. It returns an array of the removed elements.

sort and reverse

sort(compareFn) sorts in place. Without a compare function it sorts by string Unicode, which gives wrong results for numbers. reverse() reverses in place.

Example
const arr = [3, 1, 4, 1, 5];
arr.push(9);
console.log(arr); // [3,1,4,1,5,9]
const last = arr.pop();
console.log(last, arr); // 9  [3,1,4,1,5]
arr.unshift(0);
console.log(arr); // [0,3,1,4,1,5]
arr.shift();
console.log(arr); // [3,1,4,1,5]
arr.splice(2, 1, 99, 100);
console.log(arr); // [3,1,99,100,1,5]
const nums = [10, 2, 30, 4];
nums.sort((a, b) => a - b);
console.log(nums); // [2,4,10,30]
nums.reverse();
console.log(nums); // [30,10,4,2]
Pro Tip

Always pass a comparator to sort() when sorting numbers. The default lexicographic sort will silently produce wrong order for arrays like [10, 2, 30].