Stack
Prompt
Implement a Stack class with the following methods:
push(item)— adds an item to the toppop()— removes and returns the top item (returnnullif empty)peek()— returns the top item without removing it (returnnullif empty)isEmpty()— returnstrueif the stack has no itemssize()— returns the number of itemsclear()— removes all items
Playground
Use an array as the internal storage. JavaScript arrays
already have push() and pop() methods that add/remove
from the end, which is exactly what a stack does.
For peek(), you need to return the last element without
removing it. this.storage[this.storage.length - 1] gives
you the last item.
Solution
Explanation
A stack is a Last-In, First-Out (LIFO) data structure. Think of it like a stack of plates: you put plates on top, and you take plates from the top. The last plate you added is the first one you grab.
The implementation is straightforward because JavaScript arrays already behave like stacks at the end. Array.push() adds to the end, Array.pop() removes from the end. We're essentially wrapping an array with a cleaner interface.
class Stack {
constructor() {
this.storage = [];
}
push(item) {
this.storage.push(item);
}
pop() {
if (this.isEmpty()) return null;
return this.storage.pop();
}
peek() {
if (this.isEmpty()) return null;
return this.storage[this.storage.length - 1];
}
isEmpty() {
return this.storage.length === 0;
}
size() {
return this.storage.length;
}
clear() {
this.storage = [];
}
}Each method maps directly to an array operation:
push(item)usesArray.push()to add to the end (the "top" of our stack).pop()usesArray.pop()to remove from the end. We checkisEmpty()first to returnnullinstead ofundefinedwhen there's nothing to pop.peek()reads the last element usingthis.storage[this.storage.length - 1]without removing it. Same empty check.isEmpty()checks if the array length is0.size()returns the array length.clear()replaces the array with a fresh empty one.
The only thing to watch out for is the empty-state handling. Without the isEmpty() guard in pop() and peek(), calling them on an empty stack would return undefined (because [].pop() returns undefined). Returning null explicitly signals "there's nothing here" to the caller.
Stacks show up everywhere: the browser's back button is a stack of visited pages, undo/redo in text editors uses two stacks, and the JavaScript call stack itself is a stack of function calls. In interviews, stacks are commonly used to solve problems involving matching brackets, evaluating expressions, and DFS (depth-first search) traversal.
Properties vs Methods
A common interview mistake is confusing array properties and methods. length is a property — you access it without parentheses: arr.length. Methods like push(), pop(), and shift() are functions — they need parentheses to execute. Writing arr.length() throws a TypeError, and writing arr.pop without parentheses returns the function itself instead of calling it.