Stack
In one line
A stack is a LIFO (Last-In-First-Out) data structure: the last item added is the first one removed.
In simple words
A stack is a collection where you can only add and remove items from one end (the top). The last item you push on is the first one you pop off — Last-In-First-Out (LIFO). Think of a stack of plates: you add to the top and take from the top; you cannot pull a plate from the middle.
Stacks are used everywhere: the function call stack (each call pushes a frame, returning pops it), undo/redo history (push each action, pop to undo), browser back button, and expression evaluation (push operands, pop when you see an operator). The two core operations are push (add to top) and pop (remove from top), both O(1).
A stack can be implemented with an array (using push/pop methods) or a linked list. The key constraint is that access is only allowed at one end — this restricted interface is what makes it a stack, not the underlying storage.
Example
class Stack {
#items = [];
push(item) { this.#items.push(item); }
pop() { return this.#items.pop(); }
peek() { return this.#items[this.#items.length - 1]; }
get size() { return this.#items.length; }
}
const undo = new Stack();
undo.push("type A"); undo.push("type B"); undo.push("type C");
console.log(undo.pop()); // "type C" — last action undone
console.log(undo.peek()); // "type B" — next to undopush adds to the top, pop removes from the top. peek looks at the top without removing. This is LIFO order.
Related terms
Related Resources
Related Lessons
- Data Structures
Learn stacks and queues.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.