krahets/hello-algo · error · Error

Stack is empty

Error message

Stack is empty

What it means

Thrown by pop() on an array-backed stack when the stack is empty (length === 0). pop() guards before delegating to Array.pop so it never returns undefined silently. The check uses isEmpty() which tests this.#stack.length === 0.

Source

Thrown at en/codes/javascript/chapter_stack_and_queue/array_stack.js:31

    /* Get the length of the stack */
    get size() {
        return this.#stack.length;
    }

    /* Check if the stack is empty */
    isEmpty() {
        return this.#stack.length === 0;
    }

    /* Push */
    push(num) {
        this.#stack.push(num);
    }

    /* Pop */
    pop() {
        if (this.isEmpty()) throw new Error('Stack is empty');
        return this.#stack.pop();
    }

    /* Return list for printing */
    top() {
        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

  1. Check stack.isEmpty() before pop().
  2. In a loop: while (!stack.isEmpty()) { const v = stack.pop(); ... }.
  3. Validate input grammar so pops are always preceded by matching pushes.
  4. Wrap pop() in a helper returning a default when empty if that is valid for your domain.

Example fix

// before
const v = stack.pop(); // throws when empty

// after
const v = stack.isEmpty() ? null : stack.pop();
Defensive patterns

Strategy: validation

Validate before calling

if (!stack.isEmpty()) {
  const v = stack.pop();
} else {
  // handle empty stack
}

Type guard

function stackHasElements(stack) {
  return typeof stack.isEmpty === 'function' && !stack.isEmpty();
}

Try / catch

try {
  const v = stack.pop();
} catch (e) {
  if (e.message === 'Stack is empty') { /* drained */ }
  else throw e;
}

Prevention

When it happens

Trigger: Calling stack.pop() on a freshly created or fully drained stack; unbalanced push/pop pairs; recursive-emulation loops that pop past the base.

Common situations: Expression-evaluation / parenthesis matching that pops on unexpected input; undo stacks drained by redo; DFS emulation popping an empty frontier.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/bca9f4d6c6dec9e3. Report an issue: GitHub.