Enqueue values at the back and dequeue them from the front in first-in, first-out order.

Algorithm

Basic Implementation

basic.js
function render(values) {
    return values.join(" -> ");
}
const queue = [];
for (const value of [10, 20, 30]) {
    queue.push(value);
}
const removed = [];
while (queue.length > 0) {
    removed.push(queue.shift());
}
console.log(render(removed));

The queue keeps the oldest value at the front and adds new values at the back.

Step 1 - Enqueue 10, 20, 30

New values join at the back. The oldest value, 10, stays at the front.

Queue after three enqueues: front 10, then 20, then back 30.nextnext10front2030back

Step 2 - Dequeue removes 10

Removing from the front returns 10 and makes 20 the new front.

After one dequeue: removed is 10; front moves to 20.next10removed20front30back

Complexity

  • Time: O(1) per operation with a real queue
  • Space: O(n)

Implementation notes

  • JavaScript represents this lesson's queue with a mutable Array of Number values. queue.push(value) appends 10, 20, and 30 at the back without replacing the array.
  • Dequeue uses queue.shift(), which returns the front value and mutates the same array by moving later elements down one index. That preserves FIFO order for the replay, but it is O(n) per dequeue on a normal JavaScript array.
  • Removed values are collected in a second Array with removed.push(...). The replay shows queue moving from [] to [10, 20, 30], then to [20, 30] after removing 10, and finally to [] with removed = [10, 20, 30].
  • render(removed) uses values.join(" -> "), so console.log prints the deterministic output 10 -> 20 -> 30. Allocation is limited to the short input literal for the for...of, the queue array, the removed array, and the joined output string, all managed by the JavaScript runtime GC.
front The front is the oldest value still waiting in the queue.
FIFO A queue removes values in first-in, first-out order.