A stack stores data so the last item added is the first one removed. This is called last-in, first-out (LIFO). It is useful for things like undo actions, backtracking, and managing function calls.
class Stack { private items: number[] = []; push(item: number) { this.items.push(item); } pop(): number | undefined { return this.items.pop(); } print() { console.log(this.items.join(' -> ') + ' -> null'); } } const stack = new Stack(); stack.push(10); stack.push(20); stack.pop(); stack.push(30); stack.print();
The stack starts empty. Push 10, stack is [10]. Push 20, stack is [10, 20]. Pop removes 20, stack back to [10]. Push 30, stack is [10, 30]. Printing shows '10 -> 30 -> null'.
class Stack { private items: number[] = []; push(item: number) { this.items.push(item); } pop(): number { return this.items.pop()!; } } const stack = new Stack(); stack.pop();
The pop method is declared to return a number, but when the stack is empty, pop() returns undefined. This mismatch causes a TypeError at runtime.
function isBalanced(s: string): boolean {
const stack: string[] = [];
for (const char of s) {
if (char === '(') stack.push(char);
else if (char === ')') {
if (stack.length === 0) return false;
stack.pop();
}
}
return stack.length === 0;
}
console.log(isBalanced('(())()'));The function pushes '(' onto the stack and pops when it sees ')'. For '(())()', all parentheses match correctly, so the stack is empty at the end, returning true.
Function calls happen in a last-in, first-out order: the last function called must finish before the previous one continues. A stack naturally models this behavior.
