Difference between push() and unshift()?

push() adds items to the end of an array and unshift() adds them to the beginning; both mutate the array and return its new length, but unshift is slower on large arrays because every existing element must move.

The four "stack and queue" methods

MethodWhereActionReturns
push(...items)EndAddNew length
pop()EndRemoveRemoved item
unshift(...items)StartAddNew length
shift()StartRemoveRemoved item

Performance

  • push and pop are O(1) (amortised): nothing else moves.
  • unshift and shift are O(n): every element is re-indexed. On arrays with thousands of items in a hot loop this adds up. For queues with heavy use, consider a dedicated queue structure (a linked list or a circular buffer), or push and read with an index pointer.

Return values trip people up

Both return the new length, not the array. const arr2 = arr.push(4) gives a number.

Immutable versions

For state updates use spread: [...list, item] (append) or [item, ...list] (prepend).

Data structure use

  • push + pop = stack (last in, first out), e.g. undo history.
  • push + shift = queue (first in, first out), e.g. a task list.

Code example

js
1const queue = ["b", "c"];
2
3console.log(queue.push("d")); // 3 - returns the new length
4console.log(queue.unshift("a")); // 4
5console.log(queue); // ["a", "b", "c", "d"]
6
7console.log(queue.pop(), queue.shift(), queue); // "d" "a" ["b", "c"]
8
9// Immutable versions for state
10const list = [2, 3];
11console.log([...list, 4], [1, ...list], list); // [2, 3, 4] [1, 2, 3] [2, 3]
12
13// Stack (undo history)
14const undoStack = [];
15undoStack.push("type A");
16undoStack.push("type B");
17console.log("undo:", undoStack.pop()); // undo: type B
18
19// Performance difference on a large array
20const big = Array.from({ length: 50_000 }, (_, i) => i);
21let t = performance.now();
22for (let i = 0; i < 1_000; i++) big.push(i);
23const pushMs = performance.now() - t;
24t = performance.now();
25for (let i = 0; i < 1_000; i++) big.unshift(i);
26const unshiftMs = performance.now() - t;
27console.log(`unshift slower than push: ${unshiftMs > pushMs}`); // unshift slower than push: true

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app