krahets/hello-algo · error · Error

Stack is empty

Error message

Stack is empty

What it means

Thrown by peek() on a linked-list-backed stack when the internal peak pointer is null/undefined (empty). peek() returns this.#stackPeek.val; pop() calls peek() so both share the guard. The check is a truthiness test on #stackPeek, distinct from the explicit size counter #stkSize.

Source

Thrown at en/codes/javascript/chapter_stack_and_queue/linkedlist_stack.js:46

    /* Push */
    push(num) {
        const node = new ListNode(num);
        node.next = this.#stackPeek;
        this.#stackPeek = node;
        this.#stkSize++;
    }

    /* Pop */
    pop() {
        const num = this.peek();
        this.#stackPeek = this.#stackPeek.next;
        this.#stkSize--;
        return num;
    }

    /* Return list for printing */
    peek() {
        if (!this.#stackPeek) throw new Error('Stack is empty');
        return this.#stackPeek.val;
    }

    /* Convert linked list to Array and return */
    toArray() {
        let node = this.#stackPeek;
        const res = new Array(this.size);
        for (let i = res.length - 1; i >= 0; i--) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }
}

/* Driver Code */
/* Access top of the stack element */
const stack = new LinkedListStack();

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check stack.isEmpty() (or !stack.peek would throw, so guard on size/isEmpty) before pop/peek.
  2. Drain with while (!stack.isEmpty()) { const v = stack.pop(); ... }.
  3. Ensure every peek/pop is preceded by a matching push in your control flow.
  4. Wrap peek() in a helper returning null when empty if that is a valid state.

Example fix

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

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

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: Calling stack.pop() or stack.peek() on an empty stack; popping after the last node was removed (peak reset to null); unbalanced push/pop.

Common situations: DFS emulation with an empty frontier; expression parser peeking an empty operator stack; undo/redo stacks drained.

Related errors


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