Array Mutation in JavaScript
Introduction
Arrays grow and shrink as programs run. This chapter covers push, pop, shift, unshift, splice, and related methods to add, remove, and replace elements. These operations power carts, queues, and dynamic lists in real applications.
Prerequisites
Add to the End — push / pop
javascript
// push adds; pop removes from end
const stack = ["a", "b"];
stack.push("c");
console.log(stack);
const top = stack.pop();
console.log(top, stack);push can add multiple items: arr.push(x, y, z).
Add to the Start — unshift / shift
javascript
// unshift adds to front; shift removes from front
const queue = ["b", "c"];
queue.unshift("a");
console.log(queue);
const first = queue.shift();
console.log(first, queue);Shifting large arrays can be slower than popping—design matters at scale.
splice — Add, Remove, Replace in Place
javascript
// Remove 2 items starting at index 1, insert "x" and "y"
const tags = ["js", "old", "legacy", "web"];
tags.splice(1, 2, "modern", "node");
console.log(tags);Signature: splice(start, deleteCount, ...itemsToInsert)
Replacing Without Removing Count
javascript
// Replace one slot
const grades = ["A", "C", "B"];
grades.splice(1, 1, "B");
console.log(grades);concat — Non-Mutating Merge
Returns a new array:
javascript
// concat does not change originals
const a = [1, 2];
const b = [3, 4];
const merged = a.concat(b);
console.log(merged);
console.log(a, b);Spread is common today: [...a, ...b].
Clearing an Array
javascript
// Set length to 0 or replace with []
const buffer = [1, 2, 3];
buffer.length = 0;
console.log(buffer);Mini Example: Undo Stack
javascript
// Simple undo stack with push/pop
const undoStack = [];
function apply(action) {
undoStack.push(action);
console.log("Applied:", action);
}
function undo() {
const last = undoStack.pop();
console.log("Undid:", last ?? "nothing");
}
apply("add item");
apply("change color");
undo();
undo();
undo();FAQ
Does push return the new length?
Yes—const n = arr.push(item).
splice vs slice?
splice mutates; slice copies a portion (next chapter).
Can I remove by value?
filter returns new array without a value; mutating removal often uses indexOf + splice or findIndex.