Peeking elements from a Queue in Javascript

Peeking a Queue means getting the value at the head of the Queue without removing it. This allows you to inspect the next element that would be dequeued without modifying the queue structure.

Syntax

peek() {
    if (this.isEmpty()) {
        console.log("Queue Underflow!");
        return;
    }
    return this.container[0];
}

Complete Queue Implementation with Peek

class Queue {
    constructor(maxSize) {
        this.container = [];
        this.maxSize = maxSize;
    }
    
    isEmpty() {
        return this.container.length === 0;
    }
    
    isFull() {
        return this.container.length >= this.maxSize;
    }
    
    enqueue(element) {
        if (this.isFull()) {
            console.log("Queue Overflow!");
            return;
        }
        this.container.push(element);
    }
    
    dequeue() {
        if (this.isEmpty()) {
            console.log("Queue Underflow!");
            return;
        }
        return this.container.shift();
    }
    
    peek() {
        if (this.isEmpty()) {
            console.log("Queue Underflow!");
            return;
        }
        return this.container[0];
    }
    
    display() {
        console.log(this.container);
    }
}

// Example usage
let q = new Queue(5);
q.enqueue(3);
q.enqueue(4);
q.enqueue(7);

console.log("Peek:", q.peek());
q.display();

console.log("Dequeue:", q.dequeue());
console.log("Peek after dequeue:", q.peek());
q.display();
Peek: 3
[ 3, 4, 7 ]
Dequeue: 3
Peek after dequeue: 4
[ 4, 7 ]

Peek vs Dequeue Comparison

Operation Returns Front Element Removes Element Modifies Queue
peek() Yes No No
dequeue() Yes Yes Yes

Use Cases for Peek

The peek operation is useful when you need to:

  • Check what element will be processed next without processing it
  • Implement conditional logic based on the front element
  • Validate queue contents before performing operations

Conclusion

The peek() method provides read-only access to the front element of a queue. Unlike dequeue(), it doesn't modify the queue structure, making it perfect for inspecting elements before processing them.

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

771 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements