JavaScript Notes
Master the Queue data structure in JavaScript. Learn FIFO principle, enqueue/dequeue operations, circular queue, priority queue, real-world examples like task scheduling, and interview Q&A.
A Queue is a linear data structure that follows the FIFO principle — First In, First Out. The first element you add is the first one you remove. Think of a line at a coffee shop: the first person who joined the line gets served first.
💡 Key insight: A queue has two ends — the rear (where you add) and the front (where you remove). Unlike a stack, processing order matches arrival order.
Queue Visualization
Array-Based Queue (Simple)
"Queue: ['Alice', 'Bob', 'Charlie']" "Front: Alice" "Served: Alice" "Queue after dequeue: ['Bob', 'Charlie']"
⚠️ Performance note: Array.shift() is O(n) — it removes the first element and shifts all remaining elements left. For large queues, use a proper Queue class with head/tail pointers.Efficient Queue Class (O(1) Enqueue & Dequeue)
"Size: 3" "Front: Alice" "Dequeue: Alice" "Dequeue: Bob" "Queue: Charlie" "Size: 1"
Time & Space Complexity
| Operation | Time (Object-based) | Time (Array with shift) |
|---|---|---|
enqueue | O(1) | O(1) |
dequeue | O(1) | O(n) |
peek | O(1) | O(1) |
isEmpty / size | O(1) | O(1) |
| Space | O(n) | O(n) |
Real-World Application 1: Task Scheduler
'Task added: "Send email"' 'Task added: "Resize image"' 'Task added: "Generate PDF"' 'Running: "Send email"' "📧 Email sent" 'Running: "Resize image"' "🖼 Image resized" 'Running: "Generate PDF"' "📄 PDF generated" "All tasks complete"
Real-World Application 2: BFS (Breadth-First Search)
"BFS from A: ['A', 'B', 'C', 'D', 'E', 'F']"
JavaScript's Event Loop Queue
JavaScript's event loop uses queues internally:
"1 - sync" "5 - sync end" "2 - microtask" "3 - microtask 2" "4 - macrotask"
Queue vs Stack
| Queue | Stack | |
|---|---|---|
| Principle | FIFO (First In, First Out) | LIFO (Last In, First Out) |
| Add | Rear (enqueue / push) | Top (push) |
| Remove | Front (dequeue / shift) | Top (pop) |
| Real-world | Ticket line, printer, BFS | Plates, undo/redo, DFS |
| JavaScript event loop | ✅ Yes | ✅ Call stack |
When to Use a Queue
✅ Use a queue when:
- Processing items in arrival order (fair scheduling)
- Breadth-First Search graph traversal
- Message queues / event buses
- Print spoolers — jobs print in the order they were submitted
- Rate limiting — process N requests per second in order
- Streaming data — buffer data chunks for ordered processing
❌ Don't use a queue when:
- You need LIFO order → use a Stack
- You need to access by priority → use a Priority Queue
- You need random index access → use an Array
Common Mistakes
- Using
Array.shift()for high-frequency queues — it's O(n). For performance-critical code, use an object-based queue or linked list. - Confusing queue with stack — queue is FIFO; stack is LIFO.
- Not checking
isEmpty()beforedequeue()— dequeuing from an empty queue returnsundefinedwith arrays, which can cause silent bugs. - Using
unshift()to enqueue — it's O(n). Always push to the *end* (rear) and remove from the *front*.
Interview Questions
Q1. What is a queue and what principle does it follow?
A queue is a linear data structure following FIFO — First In, First Out. Elements are added at the rear (enqueue) and removed from the front (dequeue). The first element added is the first one processed.
Q2. Why is Array.shift() inefficient for a queue?
shift() removes the first element and shifts all remaining elements one position left — O(n). For a queue with frequent dequeue operations, use an object with head/tail pointers to achieve O(1) dequeue.Q3. How does the JavaScript event loop use a queue?
The event loop has a macrotask queue (setTimeout, setInterval, I/O) and a microtask queue (Promises, queueMicrotask). After the call stack is empty, all microtasks drain first (FIFO), then one macrotask is picked from the macrotask queue.
Q4. What is the difference between a queue and a priority queue?
A standard queue processes elements in arrival order (FIFO). A priority queue processes elements by priority — the highest-priority element is dequeued first, regardless of when it was added.
Q5. How do you implement a queue using two stacks?
Use one stack for enqueue (push). For dequeue, if the second stack is empty, pop all elements from the first stack into the second (reversing their order), then pop from the second. Amortised O(1) per operation.
Q6. Where are queues used in real JavaScript applications?
Task schedulers, request throttlers, print spoolers, message queues (RabbitMQ, Kafka), BFS algorithms, JavaScript's own event loop (macrotask/microtask queues), animation frame queues.
Q7. What is a circular queue and why is it used?
A circular queue (ring buffer) reuses freed array slots by wrapping the head/tail pointers modulo the capacity. It fixes the memory waste of a naive fixed-size array queue where head keeps advancing and old positions are never reused.
Key Takeaways
- A queue is FIFO — the first element in is the first one out.
- Core operations:
enqueue(add rear),dequeue(remove front),peek(read front) — all O(1) with an efficient implementation. Array.shift()is O(n) — use an object-based queue for performance-sensitive code.- Queues power BFS, task schedulers, message brokers, and JavaScript's event loop.
- Always check
isEmpty()before dequeuing to avoid undefined values or exceptions.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Queue Data Structure in JavaScript — FIFO, Enqueue & Dequeue Explained.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, data, structures, queue
Related JavaScript Master Course Topics