krahets/hello-algo · error · Error
Queue is empty
Error message
Queue is empty
What it means
Thrown by peek() on a linked-list-backed queue when size === 0. peek() returns this.#front.val; pop() calls peek() so both share the guard. The check uses this.size (a public count) rather than isEmpty().
Source
Thrown at en/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js:57
} else {
this.#rear.next = node;
this.#rear = node;
}
this.#queSize++;
}
/* Dequeue */
pop() {
const num = this.peek();
// Delete head node
this.#front = this.#front.next;
this.#queSize--;
return num;
}
/* Return list for printing */
peek() {
if (this.size === 0) throw new Error('Queue is empty');
return this.#front.val;
}
/* Convert linked list to Array and return */
toArray() {
let node = this.#front;
const res = new Array(this.size);
for (let i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
/* Driver Code */
/* Access front of the queue element */
const queue = new LinkedListQueue();View on GitHub (pinned to 69932aed18)
Solutions
- Check queue.size === 0 (or queue.isEmpty()) before pop/peek.
- Drain with while (queue.size > 0) { const v = queue.pop(); ... }.
- Track enqueue count to bound a fixed number of pops.
- If you must be defensive, catch the error as an end-of-stream signal.
Example fix
// before
while (true) { const v = queue.pop(); ... } // throws when empty
// after
while (queue.size > 0) { const v = queue.pop(); ... } Defensive patterns
Strategy: validation
Validate before calling
if (queue.size > 0) {
const v = queue.pop();
} else {
// handle empty queue
} Type guard
function queueHasElements(queue) {
return typeof queue.size === 'number' && queue.size > 0;
} Try / catch
try {
const v = queue.pop();
} catch (e) {
if (e.message === 'Queue is empty') { /* drained */ }
else throw e;
} Prevention
- Check queue.size > 0 before pop/peek.
- Drain with while (queue.size > 0) pop().
- Track enqueue count to bound a fixed number of pops.
When it happens
Trigger: Calling queue.pop() or queue.peek() on an empty queue; consuming more than produced; FIFO where front has advanced past the last node.
Common situations: BFS with an empty frontier; task/buffer queue drained; loop that pops until falsy but the throw preempts undefined.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/7fb5f63e35f75454.
Report an issue: GitHub.