TheAlgorithms/JavaScript · error · Error
Queue is Empty
Error message
Queue is Empty
What it means
Thrown by Queue.dequeue() (Error, not a typed subclass) when the queue is empty. dequeue() first calls peekFirst() which itself throws the same message on an empty queue, so the guard is effectively duplicated; either path produces 'Queue is Empty'.
Source
Thrown at Data-Structures/Queue/Queue.js:49
if (!this.head && !this.tail) {
this.head = node
this.tail = node
} else {
this.tail.next = node
this.tail = node
}
return ++this.#size
}
/**
* @description - Removes the value at the front of the queue
* @returns {*} - The first data of the queue
*/
dequeue() {
if (this.isEmpty()) {
throw new Error('Queue is Empty')
}
const firstData = this.peekFirst()
this.head = this.head.next
if (!this.head) {
this.tail = null
}
this.#size--
return firstData
}
/**
* @description - Return the item at the front of the queue
* @returns {*}View on GitHub (pinned to 5c39e87a9a)
Solutions
- Call queue.isEmpty() (or check queue.size) before dequeue().
- In a drain loop, loop while (!queue.isEmpty()) instead of a fixed count.
- Wrap dequeue in try/catch if an empty queue is an expected control-flow signal rather than a bug.
- Track enqueued count separately and never dequeue beyond it.
Example fix
// before
while (true) {
const item = queue.dequeue() // throws once empty
process(item)
}
// after
while (!queue.isEmpty()) {
process(queue.dequeue())
} Defensive patterns
Strategy: validation
Validate before calling
function safeDequeue(queue) {
if (queue.isEmpty()) return undefined
return queue.dequeue()
} Type guard
const hasItems = (queue) => !queue.isEmpty()
Try / catch
try {
return queue.dequeue()
} catch (e) {
if (e instanceof Error && /queue is empty/i.test(e.message)) return undefined
throw e
} Prevention
- Loop with while (!queue.isEmpty()) instead of a fixed count.
- Track enqueued count and never dequeue beyond it.
- Treat an empty dequeue as expected control flow only if you wrap it in try/catch by design.
- Reset dependent consumers when the queue drains to empty.
When it happens
Trigger: Calling dequeue() before any enqueue(); calling dequeue() more times than items were enqueued; draining an already-drained queue in a worker loop.
Common situations: Producer/consumer where the consumer outruns the producer; processing a batch whose advertised count exceeds enqueued items; reusing a queue after clear without resetting expectations.
Related errors
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/ab8200d2fb5d7ad0.
Report an issue: GitHub.