- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Queues in JavaScript
Stacks and Queues
Queues in JavaScript
JavaScript has no queue. The obvious implementation with shift() is quadratic, and it is the most common accidental performance bug in this whole subject.
First in, first out
Add at the back, remove from the front. A checkout line. Where a stack reverses order, a queue preserves it - which is why breadth-first search uses one.
The trap
The obvious queue is O(n) per removal
javascript
const queue = []
queue.push(1) // O(1) — fine
queue.push(2)
queue.shift() // O(n) — every remaining element slides forwardProcessing a million items this way is roughly half a trillion element moves. It will appear to hang.
