krahets/hello-algo · error · Error
Stack is empty
Error message
Stack is empty
What it means
Thrown by ArrayStack.pop when the stack is empty. pop calls Array.pop on the backing array, but the guard ensures the caller never receives undefined masquerading as a number and signals the precondition failure explicitly.
Source
Thrown at en/codes/typescript/chapter_stack_and_queue/array_stack.ts:31
/* Get the length of the stack */
get size(): number {
return this.stack.length;
}
/* Check if the stack is empty */
isEmpty(): boolean {
return this.stack.length === 0;
}
/* Push */
push(num: number): void {
this.stack.push(num);
}
/* Pop */
pop(): number | undefined {
if (this.isEmpty()) throw new Error('Stack is empty');
return this.stack.pop();
}
/* Return list for printing */
top(): number | undefined {
if (this.isEmpty()) throw new Error('Stack is empty');
return this.stack[this.stack.length - 1];
}
/* Return Array */
toArray() {
return this.stack;
}
}
/* Driver Code */
/* Access top of the stack element */
const stack = new ArrayStack();View on GitHub (pinned to 69932aed18)
Solutions
- Check isEmpty() before pop.
- Use while (!stack.isEmpty()) for draining.
- Wrap pop to return undefined on empty instead of throwing.
Example fix
// before const v = stack.pop(); // throws if empty // after const v = stack.isEmpty() ? undefined : stack.pop();
Defensive patterns
Strategy: validation
Validate before calling
const v = stack.isEmpty() ? undefined : stack.pop();
Type guard
function hasElements(s) { return typeof s.isEmpty === 'function' && !s.isEmpty(); } Try / catch
try { return stack.pop(); }
catch (e) { if (!/Stack is empty/.test(e.message)) throw e; return undefined; } Prevention
- Pair every pop with an isEmpty() check.
- Track depth in algorithm loops for cheap guards.
- Wrap pop in a helper returning undefined on empty.
When it happens
Trigger: Calling pop on a freshly created stack; popping more times than you pushed; unbalanced push/pop in expression evaluation.
Common situations: Algorithm implementations (e.g. parenthesis matching, DFS) that pop without checking depth; loops that assume the stack is non-empty.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/797b1973e7b23ada.
Report an issue: GitHub.