O'Reilly logo

Learning JavaScript Data Structures and Algorithms - Second Edition by Loiane Groner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a queue

We are now going to create our own class to represent a queue. Let's start from the basics and declare our class:

function Queue() { 
  //properties and methods go here 
} 

First, we need a data structure that will store the elements of the queue. We can use an array to do it, just like we used it for the Stack class in the previous chapter (you will notice the Queue and Stack class are very similar, just the principles for adding and removing the elements are different):

let items = []; 

Next, we need to declare the methods available for a queue:

  • enqueue(element(s)): This adds a new item (or several items) at the back of the queue.
  • dequeue(): This removes the first item from the queue (the item that is in the front of the queue). It also ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required