DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

1

Queue - Data Structures in JavaScript: Part #3

Queue is a linear data structure, similar to stack, that works on the First-In-First-Out (FIFO) principle. This is best illustrated through the following real life example. Think of people lining up at the movie theater kiosk to buy tickets. The person at the front of the line will get his or her ticket first and leave, whereas the person at the end of line will get his or her ticket much later. Anyone joining the line afterwards will obviously get their ticket after them.

Quese has two basic operations:

  • Enqueue - adding an element at the end of it
  • Dequeue - removing an element at the end of it

Look at the code below to see how this concept is exemplified in a queue class using an array.

class Queue  { 
    constructor()  { 
        this.items = []; 
    } 

   // Adds an element to the queue
   enqueue(element) {     
     this.items.push(element); 
   } 

  //Removes an element from the queue
   dequeue() { 
     this.items.shift(); 
   } 

   // returns the Front element of  the queue without removing it.
   front() {  
      if(this.items.length == 0){ 
         return "No elements in Queue";
       } 
     return this.items[0]; 
   }
}

// creating object for queue class 
var queue = new Queue(); 

// Adding elements to the queue. Queue contains [1, 2, 3, 4, 5] 
queue.enqueue(1); 
queue.enqueue(2); 
queue.enqueue(3); 
queue.enqueue(4); 
queue.enqueue(5);

// returns 1 
console.log(queue.front()); 

// removes 1 from the queue. Queue contains [2, 3, 4, 5] 
console.log(queue.dequeue()); 

// returns 2 
console.log(queue.front()); 

// removes 2. Queue contains [3, 4, 5] 
console.log(queue.dequeue()); 

Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay