krahets/hello-algo · error · Error
Queue is empty
Error message
Queue is empty
What it means
Thrown by ArrayQueue.peek when the queue is empty. peek returns nums[front]; with queSize === 0 the front pointer points at no logical element, so the method throws. pop calls peek first and re-throws this error, so popping an empty queue surfaces the same message.
Source
Thrown at en/codes/typescript/chapter_stack_and_queue/array_queue.ts:58
// Add num to the rear of the queue
const rear = (this.front + this.queSize) % this.capacity;
// Front pointer moves one position backward
this.nums[rear] = num;
this.queSize++;
}
/* Dequeue */
pop(): number {
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(): number {
if (this.isEmpty()) throw new Error('Queue is empty');
return this.nums[this.front];
}
/* Return Array */
toArray(): number[] {
// 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 isEmpty() (or size() === 0) before pop/peek.
- Drain with while (!queue.isEmpty()).
- Wrap pop in a helper returning undefined on empty.
Example fix
// before const v = queue.pop(); // throws if empty // after const v = queue.isEmpty() ? undefined : queue.pop();
Defensive patterns
Strategy: validation
Validate before calling
const v = queue.isEmpty() ? undefined : queue.pop();
Type guard
function hasElements(q) { return typeof q.isEmpty === 'function' && !q.isEmpty(); } Try / catch
try { return queue.pop(); }
catch (e) { if (!/Queue is empty/.test(e.message)) throw e; return undefined; } Prevention
- Always check isEmpty() before pop/peek.
- Drain with while (!queue.isEmpty()).
- In producer/consumer setups, gate pops on size > 0.
When it happens
Trigger: Calling pop or peek before any push; dequeueing more items than were enqueued; concurrent producers/consumers where the consumer outruns production.
Common situations: Polling loops without an emptiness check; queue drained then peeked again; capacity/front desync after failed operations.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/34c708b82a9b5b06.
Report an issue: GitHub.