March 24
Stack
What a stack is, why LIFO order shows up so often, and when push/pop is already the right mental model.
What it is
A stack is a LIFO structure:
last in, first out.
The most recent item is the first one to come back out.
In JavaScript
The simplest version uses an array with push and pop:
const stack: string[] = []
stack.push('(')
stack.pop()
When to use it
It usually fits when the problem asks you to:
- undo the most recent step
- close something that was opened before
- keep temporary context
Better question
Instead of memorizing the name, ask:
- does the most recently opened item need to be handled first?
- is there a natural undo order here?
- do I need short, reversible history?
Share this page
Copy the link manually from the field below.