JavaScriptEasy
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
| Method | Where | Action | Returns |
|---|---|---|---|
push(...items) | End | Add | New length |
pop() | End | Remove | Removed item |
unshift(...items) | Start | Add | New length |
shift() | Start | Remove | Removed item |
Performance
pushandpopare O(1) (amortised): nothing else moves.unshiftandshiftare 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"];23console.log(queue.push("d")); // 3 - returns the new length4console.log(queue.unshift("a")); // 45console.log(queue); // ["a", "b", "c", "d"]67console.log(queue.pop(), queue.shift(), queue); // "d" "a" ["b", "c"]89// Immutable versions for state10const list = [2, 3];11console.log([...list, 4], [1, ...list], list); // [2, 3, 4] [1, 2, 3] [2, 3]1213// Stack (undo history)14const undoStack = [];15undoStack.push("type A");16undoStack.push("type B");17console.log("undo:", undoStack.pop()); // undo: type B1819// Performance difference on a large array20const 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.