Understanding Queue Data Structure in JavaScript
Introduction
A Queue is a fundamental data structure that follows the First-In-First-Out (FIFO) principle. This means the **first element added** is the **first one to be removed**. 🛎️ In JavaScript, queues can be implemented using arrays with methods like push() and shift().
📌 What is a Queue?
Queues are used in scenarios where order matters, such as task scheduling, event handling, or print job management. Common operations include:
- ✔️ enqueue(element) — Add an element to the end of the queue
- ✔️ dequeue() — Remove the element from the front of the queue
- ✔️ peek/front() — View the front element without removing it
- ✔️ isEmpty() — Check if the queue is empty
💡 Implementing Queue Using Arrays
Queue using array
const queue = [];
// Enqueue elements
queue.push(10);
queue.push(20);
queue.push(30);
console.log(queue); // [10, 20, 30]
// Dequeue element
const removed = queue.shift();
console.log(removed); // 10
console.log(queue); // [20, 30]
// Peek front element
const front = queue[0];
console.log(front); // 20🧵 Example: Custom Queue Class
Queue class implementation
class Queue {
constructor() {
this.items = [];
}
// Add element
enqueue(element) {
this.items.push(element);
}
// Remove element
dequeue() {
if (this.isEmpty()) return "Queue is empty";
return this.items.shift();
}
// View front element
front() {
if (this.isEmpty()) return "Queue is empty";
return this.items[0];
}
// Check if queue is empty
isEmpty() {
return this.items.length === 0;
}
// Display queue
print() {
console.log(this.items);
}
}
// Usage
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.print(); // [1, 2, 3]
console.log(queue.dequeue()); // 1
console.log(queue.front()); // 2🔗 Applications of Queue
- 📌 Task scheduling (e.g., CPU or event loop)
- 📌 Handling asynchronous events
- 📌 Print job management
- 📌 Breadth-first search (BFS) in graphs
⚠️ Important Notes
Note
- Queues follow the **FIFO** principle strictly.
- JavaScript arrays can implement queues using push() and shift(), but shift() has O(n) complexity.
- For efficient large-scale queues, consider using **linked lists** or **deque** libraries.
📊 Quick Reference Table
| Operation | Method / Example | Effect |
|---|---|---|
| Enqueue | queue.push(10) | Adds 10 to the rear |
| Dequeue | queue.shift() | Removes and returns front element |
| Peek / Front | queue[0] | View front element without removing |
| IsEmpty | queue.length === 0 | Check if queue is empty |
>>"Queues are like lines at a ticket counter — first come, first served." 🎟️
🔥 Summary
A queue is a simple but essential data structure following FIFO. In JavaScript, arrays provide a basic queue implementation, and custom classes can give you full control. Queues are widely used in scheduling, event handling, and graph algorithms.