A queue is "first in, first out" (FIFO): enqueue adds at the back, dequeue removes from the front. Where the stack serves the most recent item, the queue serves in arrival order, it is the data structure of fairness. Task scheduling, print jobs, request handling, buffering, and breadth-first search all promise "things get processed in the order they arrived", and a queue is that promise kept.
Implementation detail that matters: an array used naively (shift() to dequeue) pays O(n) per operation because everything shifts left. Real queues either track head/tail indices into a ring buffer (wrap around the end, O(1) everything) or use a linked list with head AND tail pointers. JavaScript's clean answer for BFS-style usage is often two-index bookkeeping over one array, or pushing and index-walking. Know why the trick exists, shifting is the hidden O(n²) in many beginners' BFS.
| Operation / case | Cost | Notes |
|---|---|---|
| enqueue (back) | O(1) | linked: tail pointer; ring: index bump |
| dequeue (front) | O(1) | linked: head pointer; ring: index bump |
| peek (front) | O(1) | — |
| Array with shift() | O(n) | shifts everything, avoid in hot paths |
A ring buffer queue, all operations O(1)
class RingQueue {
#buf;
#head = 0; // index of the front element
#count = 0; // how many elements are stored
constructor(capacity = 8) { this.#buf = new Array(capacity); }
enqueue(v) {
if (this.#count === this.#buf.length) this.#grow(); // full → double
const tail = (this.#head + this.#count) % this.#buf.length; // wrap around
this.#buf[tail] = v;
this.#count++;
}
dequeue() {
if (this.#count === 0) return undefined;
const v = this.#buf[this.#head];
this.#head = (this.#head + 1) % this.#buf.length; // wrap around
this.#count--;
return v;
}
#grow() {
const bigger = new Array(this.#buf.length * 2);
for (let i = 0; i < this.#count; i++) bigger[i] = this.#buf[(this.#head + i) % this.#buf.length];
this.#buf = bigger;
this.#head = 0;
}
}