push, pop, shift & unshift in JavaScript
The four end-methods mutate in place: push appends (returning the new length), pop removes the last (returning it), shift removes the first (returning it, O(n) reindex), unshift prepends (returning the new length, also O(n)). All return something useful β lengths for adders, elements for removers β enabling terse pipelines.
push/pop form an efficient stack (both O(1) amortized); shift/unshift form a slow queue (prefer index pointers or real queues for hot paths). Every method mutates the same array β copy first (slice()) when the original must survive.
push appends, returns length
arr.push(x) adds at the end β the return is the new length, not the array.
pop removes last, returns it
let last = arr.pop() β the removed element comes back; empty arrays yield undefined.
shift/unshift work the front
shift removes first, unshift prepends β both O(n) from reindexing, fine occasionally, costly in loops.
All mutate in place
The array itself changes β slice() first when callers must keep the original intact.
let stack = [];stack.push(1);stack.push(2);console.log(stack.pop(), stack.length);Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.