krahets/hello-algo · error · Error
The Deque Is Empty.
Error message
The Deque Is Empty.
What it means
Thrown by peekFirst() on an array-backed deque when the deque is empty. peekFirst() reads the front element without removing it; popFirst() delegates to it. The guard prevents reading this.#nums[this.#front] on an empty structure where the index is meaningless.
Source
Thrown at en/codes/javascript/chapter_stack_and_queue/array_deque.js:88
/* Rear of the queue dequeue */
popFirst() {
const num = this.peekFirst();
// Move front pointer backward by one position
this.#front = this.index(this.#front + 1);
this.#queSize--;
return num;
}
/* Access rear of the queue element */
popLast() {
const num = this.peekLast();
this.#queSize--;
return num;
}
/* Return list for printing */
peekFirst() {
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
return this.#nums[this.#front];
}
/* Driver Code */
peekLast() {
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
// Initialize double-ended queue
const last = this.index(this.#front + this.#queSize - 1);
return this.#nums[last];
}
/* Return array for printing */
toArray() {
// Elements enqueue
const res = [];
for (let i = 0, j = this.#front; i < this.#queSize; i++, j++) {
res[i] = this.#nums[this.index(j)];
}View on GitHub (pinned to 69932aed18)
Solutions
- Check deque.isEmpty() before peekFirst()/popFirst().
- In a consume loop use while (!deque.isEmpty()) { const v = deque.popFirst(); ... }.
- Return a sentinel/Option from a wrapper if empty-peek is a valid application state.
- Track enqueue/dequeue counts if you need to bound a fixed number of operations.
Example fix
// before const front = deque.peekFirst(); // throws when empty // after const front = deque.isEmpty() ? null : deque.peekFirst();
Defensive patterns
Strategy: validation
Validate before calling
if (!deque.isEmpty()) {
const front = deque.peekFirst();
} else {
// handle empty deque
} Type guard
function dequeHasFront(deque) {
return typeof deque.isEmpty === 'function' && !deque.isEmpty();
} Try / catch
try {
const front = deque.peekFirst();
} catch (e) {
if (e.message === 'The Deque Is Empty.') { /* empty */ }
else throw e;
} Prevention
- Check isEmpty() before peekFirst()/popFirst().
- Drain with while (!deque.isEmpty()) popFirst().
- Wrap peek in a helper returning null for empty if that is a valid state.
When it happens
Trigger: Calling peekFirst() or popFirst() on an empty deque; reading the front before any push; dequeuing more than was enqueued.
Common situations: BFS/level-order traversal peeking at empty frontier; producer-consumer where consumer races ahead; calling popFirst in a loop without an emptiness guard.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/ce531b7890502a08.
Report an issue: GitHub.