Learn JavaScript
❯ arrays.stack_methods

push, pop, shift & unshift in JavaScript

$concept

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.

$how it works
1

push appends, returns length

arr.push(x) adds at the end β€” the return is the new length, not the array.

2

pop removes last, returns it

let last = arr.pop() β€” the removed element comes back; empty arrays yield undefined.

3

shift/unshift work the front

shift removes first, unshift prepends β€” both O(n) from reindexing, fine occasionally, costly in loops.

4

All mutate in place

The array itself changes β€” slice() first when callers must keep the original intact.

$example
let stack = [];
stack.push(1);
stack.push(2);
console.log(stack.pop(), stack.length);
Output
2 1
1Two pushes build [1, 2] β€” lengths 1 then 2 (returns ignored here).
2pop removes and returns the last element 2, leaving length 1.
32 1 prints β€” LIFO order from three method calls.
$use cases
Stacks (undo, backtracking, DFS) via push/pop
Small queues via shift/unshift where O(n) doesn't matter
Draining arrays with while (arr.length) pop() loops
Copying before mutating shared arrays

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.