JavaScript Notes
Master the Stack data structure in JavaScript. Learn LIFO principle, push/pop operations, real-world use cases, array and class implementations, and stack interview questions with answers.
A Stack is a linear data structure that follows the LIFO principle — Last In, First Out. The last element you add is the first one you remove. Think of it as a pile of plates: you always add and remove from the top.
💡 Key insight: A stack has only two primary operations:push(add to top) andpop(remove from top). Both run in O(1) time — instant, regardless of stack size.
Stack Visualization
Array-Based Stack (Quick & Practical)
JavaScript arrays have built-in push and pop that work perfectly as a stack:
"Stack: ['A', 'B', 'C']" "Top: C" "Popped: C" "Stack after pop: ['A', 'B']" "isEmpty: false"
Stack Class Implementation
"Size: 3" "Peek: 30" "Pop: 30" "Peek now: 20" "Stack: 10 → 20"
Time & Space Complexity
| Operation | Time Complexity | Why |
|---|---|---|
push | O(1) | Add to end of array |
pop | O(1) | Remove from end of array |
peek | O(1) | Read last element |
isEmpty | O(1) | Check length |
size | O(1) | Read length property |
| Space | O(n) | n = number of elements |
Real-World Application 1: Undo/Redo
class TextEditor {
#content = "";
#undoStack = new Stack();
#redoStack = new Stack();
type(text) {
this.#undoStack.push(this.#content);
this.#redoStack = new Stack(); // clear redo on new action
this.#content += text;
console.log("Content:", this.#content);
}
undo() {
if (this.#undoStack.isEmpty()) {
console.log("Nothing to undo");
return;
}
this.#redoStack.push(this.#content);
this.#content = this.#undoStack.pop();
console.log("Undo → Content:", this.#content);
}
redo() {
if (this.#redoStack.isEmpty()) {
console.log("Nothing to redo");
return;
}
this.#undoStack.push(this.#content);
this.#content = this.#redoStack.pop();
console.log("Redo → Content:", this.#content);
}
}
const editor = new TextEditor();
editor.type("Hello");
editor.type(", World");
editor.undo();
editor.undo();
editor.redo();"Content: Hello" "Content: Hello, World" "Undo → Content: Hello" "Undo → Content: " "Redo → Content: Hello"
Real-World Application 2: Balanced Parentheses
true false false
The JavaScript Call Stack
JavaScript itself uses a stack internally — the call stack — to track function calls:
function c() { console.log("C running"); }
function b() { c(); console.log("B running"); }
function a() { b(); console.log("A running"); }
a();"C running" "B running" "A running"
"Stack overflow" occurs when too many nested calls fill the stack (classic example: infinite recursion).
When to Use a Stack
✅ Use a stack when:
- You need to reverse a sequence
- You need undo/redo functionality
- You need to match/validate paired symbols
- You're implementing DFS (Depth-First Search)
- You're evaluating arithmetic expressions
- You're managing browser history (back button)
❌ Don't use a stack when:
- You need to process elements in arrival order (use a Queue)
- You need random access by index (use an Array)
- You need sorted access by priority (use a Priority Queue)
Common Mistakes
- Popping from an empty stack — always check
isEmpty()before callingpop(), or handle the error. - Using
shift()/unshift()instead ofpush()/pop()—shiftandunshiftoperate on the front of an array in O(n). For a stack, always use the *end* of the array. - Confusing stack with queue — stack is LIFO; queue is FIFO. They are different data structures.
- Not clearing the redo stack on new actions — classic bug in undo/redo implementations.
Interview Questions
Q1. What is a stack and what principle does it follow?
A stack is a linear data structure that follows LIFO — Last In, First Out. The last element added is the first one removed. Primary operations arepush(add to top) andpop(remove from top).
Q2. What is the time complexity of push and pop in a stack?
Both are O(1) — constant time. When using a JavaScript array as a stack,push()andpop()both operate on the end of the array and run in O(1) amortised time.
Q3. How is a stack used internally by JavaScript?
JavaScript uses a call stack to track function invocations. Each function call pushes a frame onto the stack; when the function returns, the frame is popped. If the stack overflows (e.g., infinite recursion), you get a "Maximum call stack size exceeded" error.
Q4. How would you implement an undo/redo feature using stacks?
Maintain two stacks:undoStackandredoStack. On every action, push the previous state toundoStack. Onundo, pop fromundoStack, push current state toredoStack. Onredo, pop fromredoStack, push current state toundoStack.
Q5. How do you check for balanced parentheses using a stack?
Iterate the string. Push opening brackets onto the stack. When a closing bracket is found, pop from the stack and verify it matches the expected opening bracket. If not, or if the stack is non-empty at the end, the string is unbalanced.
Q6. What is the difference between peek and pop?
peekreads the top element without removing it.popremoves and returns the top element. Usepeekwhen you need to inspect the top without modifying the stack.
Q7. How would you reverse a string using a stack?
``js function reverseString(str) { const stack = [...str]; // push each char return stack.reverse().join(""); // pop each char } console.log(reverseString("hello")); // "olleh" ``Key Takeaways
- A stack is LIFO — the last element in is the first one out.
- Core operations:
push(add top),pop(remove top),peek(read top) — all O(1). - JavaScript arrays are a natural stack implementation:
push()adds to end,pop()removes from end. - Classic uses: undo/redo, balanced brackets, DFS, browser back history, call stack.
- Always check
isEmpty()before callingpop()to avoid underflow errors.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Stack Data Structure in JavaScript — LIFO, Push, Pop Explained.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, data, structures, stack
Related JavaScript Master Course Topics