JavaScript Program to Implement a Queue Data Structure in Browser

What we are going to look at today is JavaScript Program to Implement a Queue Data Structure in Browser We are going to be very clear about this topic. We hope that all the skepticism on this topic will be resolved through this article.

JavaScript Program to Implement a Queue Data Structure in Browser

JavaScript Program to Implement a Queue Data Structure in Browser

// program to implement queue data structure

class Queue {
    constructor() {
        this.items = [];
    }
    
    // add element to the queue
    enqueue(element) {
        return this.items.push(element);
    }
    
    // remove element from the queue
    dequeue() {
        if(this.items.length > 0) {
            return this.items.shift();
        }
    }
    
    // view the last element
    peek() {
        return this.items[this.items.length - 1];
    }
    
    // check if the queue is empty
    isEmpty(){
       return this.items.length == 0;
    }
   
    // the size of the queue
    size(){
        return this.items.length;
    }
 
    // empty the queue
    clear(){
        this.items = [];
    }
}

let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(4);
queue.enqueue(8);
console.log(queue.items);

queue.dequeue();
console.log(queue.items);

console.log(queue.peek());

console.log(queue.isEmpty());

console.log(queue.size());

queue.clear();
console.log(queue.items);

Read Also: JavaScript Program to Check if a Number is Float or Integer Using Regular Expression in Browser

Final Words

We hope you find the JavaScript Program to Implement a Queue Data Structure in Browser useful. And please let us know if you have any doubts about this article.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment