Arrays
Stack: push() and pop()
Last put in, first taken out.
Why it exists
Many problems are "nested": brackets inside brackets, a function calling a function, a page opened from a page. You have to go back in reverse order — to the latest first. A stack keeps exactly that order and only gives access to the last item, so it's hard to get wrong.
Where it's used
- Checking brackets and parsing nested structures (JSON, HTML).
- Undo: each action goes on a stack, and Ctrl+Z takes off the last one.
- The Back button and navigation history.
- The call stack: how the engine remembers where to return from a function — you see it in an error message.
Syntax
const stack = [];
stack.push(item); // put on top
stack.pop(); // take the top off
stack.at(-1); // look at the top without removing itExamples
const stack = [1, 2];
stack.push(3);
stack.pop(); // → 3const history = [];
history.push("home");
history.push("catalogue");
history.push("product");
history.pop();
history.at(-1); // → "catalogue"[].pop(); // → undefinedconst stack = [];
for (const ch of "([])") {
if (ch === "(" || ch === "[") stack.push(ch);
else stack.pop();
}
stack.length; // → 0Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The array is used only at its end: push adds an item to the end, pop removes the last one and returns it. Both are fast — the other items don't move.
If the array is empty, pop returns undefined and doesn't throw. That's handy in checks like stack.pop() !== expected.
To look at the top item without removing it: stack.at(-1) or stack[stack.length - 1].
Both methods change the array in place.
For a queue ("first in, first out"), use push and shift, but shift moves every item and is slow on big arrays.
Traps
How it differs from…
array.push()push is half of a stack; it has its own entry.
- Changing arrays and copies
push and
popchange the array in place — keep that in mind if the stack is shared.
When to pick something else
If you need access to any item, not just the last, or "first in, first out" order, a stack doesn't fit: you need an ordinary array with indexes, or a queue.