Stacks
Last In, First Out. The simplest constraint you can add to a list — yet it powers your programming language's function calls, your browser's back button, your editor's undo history, and every recursive algorithm ever written.
What is a stack data structure?
A stack is a Last In, First Out (LIFO) collection: you push items onto the top and pop them off the top, like a stack of plates. Push, pop and peek are all O(1). Stacks power function calls (the call stack), undo history, the browser's back button, bracket matching and depth-first search.
const stack = [];
stack.push(1); stack.push(2); // [1, 2]
stack.at(-1); // peek → 2
stack.pop(); // 2
function isBalanced(s) { // classic: matching brackets
const pairs = { ")": "(", "]": "[", "}": "{" }, st = [];
for (const ch of s) {
if ("([{".includes(ch)) st.push(ch);
else if (pairs[ch] && st.pop() !== pairs[ch]) return false;
}
return st.length === 0;
}The physical model
Picture a stack of dinner plates. You always add to the top and take from the top. There's no accessing the bottom plate without first removing every plate above it. This single constraint — only interact with the top — is the entire definition of a stack.
Plate Stack
Add and remove only from the top of a stack of plates.
Function calls
The most recent function call is always resolved first.
Undo history
The most recent edit is always undone first.
Live call stack demo
This simulates what your language runtime does on every function call. Push adds a new frame on top. Pop removes the topmost frame — just like a function returning to its caller.
Operations
Log
▶ Stack initialized with [3, 7, 12, 5]
Interactive sandbox — code a Stack
Now it's your turn. Implement a dynamic Stack in JavaScript and use it to validate whether brackets inside an expression are nested correctly. Edit the code below and run it live!
Code Editor
<button id="push">push</button> <button id="pop">pop</button> <button id="peek">peek</button>
<div id="stack"></div>
<p id="out"></p>Preview
Implementation with a dynamic array
A stack is just a dynamic array with a rule: only touch the last element. No separate data structure is needed.
1Stack uses a dynamic array internally23push(value):4 array.append(value) // O(1) amortised5 top <- last element67pop():8 if isEmpty(): error9 value <- array[last]10 array.removeLast() // O(1)11 return value1213peek():14 if isEmpty(): error15 return array[last] // O(1), no removal1617isEmpty():18 return array.length = 0
How the call stack actually works
Every time your program calls a function, the runtime pushes a stack frameonto the call stack. Each frame stores the function's local variables, parameters, and the return address. When the function returns, its frame is popped and execution continues exactly where it left off.
main() calls compute(5)
Frame for compute(5) pushed onto call stack. main() pauses.
↑ top of stack
compute() calls helper(5)
Frame for helper(5) pushed. compute() pauses. Stack now has 3 frames.
↑ top of stack
helper() returns 25
helper's frame popped. Execution resumes in compute() with return value 25.
↑ top of stack
compute() returns 30, main() finishes
compute's frame popped, then main's. Stack empty. Program ends.
Classic stack algorithms
Balanced parentheses
Push opening brackets. On every closing bracket, pop and verify it matches. If the stack is empty at the end, brackets are balanced. Compilers use this exact algorithm.
Undo / Redo
Maintain two stacks: undoStack and redoStack. Every action is pushed to undoStack. Undo pops from undoStack and pushes to redoStack. Redo reverses this.
Browser history
Navigating to a new page pushes it onto the back-stack. The Back button pops from back-stack and pushes to forward-stack. Forward pops from forward-stack.
Expression evaluation
Parse arithmetic left-to-right. Numbers go to an operand stack. Operators go to an operator stack. When an operator of lower/equal precedence arrives, pop and evaluate.
Time complexity
Constant time
Constant time
Constant time
Linear time
🎯 Quick Check
You push A, then B, then C onto a stack. You then call pop() twice. What is now on top?
Stacks: summary
Key points
- A JavaScript array with
pushandpopis a perfectly good stack. - Recursion uses the call stack implicitly; you can convert recursion to a loop with an explicit stack.
- "Stack overflow" means the call stack ran out of space.
Frequently asked questions
›What is the difference between a stack and a queue?
A stack is LIFO (the last item added comes out first). A queue is FIFO (the first item added comes out first).
›Where are stacks used in real life?
Undo/redo, browser back navigation, expression evaluation, syntax checking in compilers, and depth-first search.