krahets/hello-algo · error · Error
Queue is empty
Error message
Queue is empty
What it means
Thrown by peek() on an array-backed circular queue when empty. peek() returns this.#nums[this.#front]; pop() calls peek() first so pop also surfaces this error. The guard prevents returning undefined from an empty slot and keeps the front pointer arithmetic honest.
Source
Thrown at en/codes/javascript/chapter_stack_and_queue/array_queue.js:57
// Add num to the rear of the queue
const rear = (this.#front + this.size) % this.capacity;
// Front pointer moves one position backward
this.#nums[rear] = num;
this.#queSize++;
}
/* Dequeue */
pop() {
const num = this.peek();
// Move front pointer backward by one position, if it passes the tail, return to array head
this.#front = (this.#front + 1) % this.capacity;
this.#queSize--;
return num;
}
/* Return list for printing */
peek() {
if (this.isEmpty()) throw new Error('Queue is empty');
return this.#nums[this.#front];
}
/* Return Array */
toArray() {
// Elements enqueue
const arr = new Array(this.size);
for (let i = 0, j = this.#front; i < this.size; i++, j++) {
arr[i] = this.#nums[j % this.capacity];
}
return arr;
}
}
/* Driver Code */
/* Access front of the queue element */
const capacity = 10;
const queue = new ArrayQueue(capacity);View on GitHub (pinned to 69932aed18)
Solutions
- Check queue.isEmpty() (or queue.size === 0) before pop/peek.
- Use while (!queue.isEmpty()) { const v = queue.pop(); ... } for draining.
- Track enqueue count to bound a fixed number of pops.
- If pop must be defensive, catch the error and treat as end-of-stream.
Example fix
// before
while (true) { const v = queue.pop(); ... } // throws when empty
// after
while (!queue.isEmpty()) { const v = queue.pop(); ... } Defensive patterns
Strategy: validation
Validate before calling
if (!queue.isEmpty()) {
const v = queue.pop();
} else {
// handle empty queue
} Type guard
function queueHasElements(queue) {
return typeof queue.isEmpty === 'function' && !queue.isEmpty();
} Try / catch
try {
const v = queue.pop();
} catch (e) {
if (e.message === 'Queue is empty') { /* drained */ }
else throw e;
} Prevention
- Check isEmpty() before pop/peek.
- Drain with while (!queue.isEmpty()) 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; dequeuing more than was enqueued; FIFO processing where the consumer outpaces the producer.
Common situations: BFS frontier drained; message/buffer queue consumed faster than filled; loop that pops until falsy (but throw interrupts before undefined).
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/e94bc4d5872451ab.
Report an issue: GitHub.