krahets/hello-algo · error · Error

スタックが空

Error message

スタックが空

What it means

Thrown by the array-based stack's pop when the stack is empty. The guard prevents calling Array.pop semantics on an already-empty internal array and avoids returning undefined. The check uses this.#stack.length === 0 via isEmpty().

Source

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

    /* スタックの長さを取得 */
    get size() {
        return this.#stack.length;
    }

    /* スタックが空かどうかを判定 */
    isEmpty() {
        return this.#stack.length === 0;
    }

    /* プッシュ */
    push(num) {
        this.#stack.push(num);
    }

    /* ポップ */
    pop() {
        if (this.isEmpty()) throw new Error('スタックが空');
        return this.#stack.pop();
    }

    /* スタックトップの要素にアクセス */
    top() {
        if (this.isEmpty()) throw new Error('スタックが空');
        return this.#stack[this.#stack.length - 1];
    }

    /* Array を返す */
    toArray() {
        return this.#stack;
    }
}

/* Driver Code */
/* スタックを初期化 */
const stack = new ArrayStack();

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check stack.isEmpty() before pop().
  2. Use while (!stack.isEmpty()) for drain loops.
  3. Return a sentinel (e.g. null/undefined) when empty rather than throwing.
  4. Ensure push/pop are balanced in your algorithm.

Example fix

// before
const top = stack.pop();  // throws if empty

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

Strategy: validation

Validate before calling

function safePop(stack) {
  return stack.isEmpty() ? null : stack.pop();
}

Type guard

const isNonEmpty = (s) => typeof s.isEmpty === 'function' && !s.isEmpty();

Try / catch

try {
  return stack.pop();
} catch (e) {
  if (e instanceof Error && e.message === 'スタックが空') return null;
  throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a freshly created stack with no pushes; popping more times than you pushed; popping in a loop without an empty check.

Common situations: Bracket/expression matching where input is unbalanced; recursion simulation that over-pops; calling pop without verifying state.

Related errors


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