Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove elements from a queue using Javascript
Dequeuing elements from a Queue means removing them from the front/head of the queue. We are taking the start of the container array to be the head of the queue as we'll perform all operations with respect to it.
Hence, we can implement the dequeue function as follows:
Syntax
dequeue() {
// Check if queue is empty
if (this.isEmpty()) {
console.log("Queue Underflow!");
return;
}
return this.container.shift();
}
Complete Queue Implementation
class Queue {
constructor(maxSize) {
this.container = [];
this.maxSize = maxSize;
}
isEmpty() {
return this.container.length === 0;
}
enqueue(element) {
if (this.container.length >= this.maxSize) {
console.log("Queue Overflow!");
return;
}
this.container.push(element);
}
dequeue() {
// Check if empty
if (this.isEmpty()) {
console.log("Queue Underflow!");
return;
}
return this.container.shift();
}
display() {
console.log(this.container);
}
}
let q = new Queue(2);
q.dequeue(); // Try to dequeue from empty queue
q.enqueue(3);
q.enqueue(4);
console.log("Dequeued element:", q.dequeue());
q.display();
Queue Underflow! Dequeued element: 3 [ 4 ]
How It Works
The dequeue operation follows these steps:
- Check if empty: Prevent underflow by checking if the queue has elements
-
Remove from front: Use
shift()to remove the first element - Return element: Return the removed element to the caller
Key Points
| Operation | Method Used | Time Complexity |
|---|---|---|
| Dequeue | array.shift() |
O(n) - elements need to be shifted |
| Check Empty | length === 0 |
O(1) |
Conclusion
The dequeue operation removes elements from the front of the queue following FIFO principle. Always check for underflow conditions to prevent errors when removing from an empty queue.
Advertisements
