Implement Queue data structure in Javascript

You, Data StructureJavascript
Back

Queue in javascript : hashnode link

The Queue is the data structure that works on FIFO Principle, which is the abbreviation for "First In First Out".

Queues can have various applications:

Let's suppose you are making a service that requires you to send the email, but you don't want your program to wait for mailing to finish. Then you can send that particular task to the mailing queue and it will take control of sending all the mails in FIFO manner.

Now let's implement some functionality of the queue

The queue has some operations such as:

  1. enqueue which will add the elements at the end of the queue.

  2. Dequeue removes the element from the start of the queue.

  3. Front To find out the element at the beginning of the queue.

  4. Size function will give you the size of the queue.

  5. Empty function will check if the queue is empty or not, and return us the boolean value.

  6. Print function will print the whole queue for us.


function Queue() {
  let items = [];


  this.enqueue = function (element) {
    items.push(element);
  };

  this.dequeue = function () {
    return items.shift();
  };

  this.front = function () {
    return items[0];
  };

   this.size = function () {
    return items.length;
  };

  this.isEmpty = function () {
    return items.length === 0;
  };

    this.print = function () {
    console.log(items);
  };

}

Result :

const q = new Queue();

q.enqueue(10); // [10]      : enqueue from end
q.enqueue(20); // [ 10, 20] : enqueue from end
q.dequeue();   // [ 20]	 : dequeue from start
q.print();     // prints the whole queue
console.log(q.size()); // return the size : i.e 1
© Jagdish Parihar.RSS