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.

10 20 30 40 FRONT REAR Dequeue Queue Dequeue Operation Elements are removed from the FRONT (FIFO - First In, First Out)

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:

  1. Check if empty: Prevent underflow by checking if the queue has elements
  2. Remove from front: Use shift() to remove the first element
  3. 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.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements