Peeking elements from a Queue in Javascript


Peeking a Queue means getting the value at the head of the Queue. So we can implement the peek function as follows − 

EXample

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

You can check if this function is working fine using − 

Example

let q = new Queue(2);
q.enqueue(3);
q.enqueue(4);
console.log(q.peek());
q.display();

Output

This will give the output −

3
[ 3, 4 ]

As you can see here, peek() differs from dequeue in that it just returns the front value without removing it.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 15-Jun-2020

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements