A queue is a linear data structure where the first value added is the first value removed.
This rule is called FIFO, which means First In, First Out.
Core operations
enqueue(value)adds a value to the rear.dequeue()removes a value from the front.front()reads the next value to leave.isEmpty()checks whether the queue has no values.
Mental model
Think of people standing in a line. The first person to join the line is served first.
front -> 10, 20, 30 <- rear
JavaScript implementation
class Queue {
constructor() {
this.items = [];
}
enqueue(value) {
this.items.push(value);
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
}
For large queues, avoid shift() because it moves every remaining item. A better production queue tracks a frontIndex.
Where queues show up
- Task scheduling
- Breadth-first search
- Print jobs
- Message processing
- Rate-limited workers
Complexity
- Enqueue:
O(1) - Dequeue with
shift():O(n) - Dequeue with a front pointer:
O(1) - Peek front:
O(1)
Practice links
Use the visualizer below to enqueue and dequeue values.
Interactive walkthrough
Queue Visualizer
Enqueue at the rear and dequeue from the front.