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

  1. Call queue.isEmpty() (or check queue.size) before dequeue().
  2. In a drain loop, loop while (!queue.isEmpty()) instead of a fixed count.
  3. Wrap dequeue in try/catch if an empty queue is an expected control-flow signal rather than a bug.
  4. 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

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.