Making a Queue in Javascript

Queue’s in javascript will behave like an array but can only perform the method’s such as .unshift() which will add an element to the beginning of an array and .pop() which will remove the last element in the array. Sometimes you only want an array to behave in this manner and want to make it clear that this is what you are doing.

A queue is basically a line, such as one you would stand in to get onto a theme park ride. One item (person) enters the line and waits while all the other people ahead of them get removed from the line when it is their turn.

A Queue

To be clear, we are minimizing the functionality of an array to do only a set of certain actions. Javascript arrays have many methods you can perform on them, however, we are limiting it to just two methods. It is good to know how to do this as this question is a common interview data structure and algorithm question. It also shows that you know how to construct javascript classes.

We will create a Javascript class of Queue that will be an empty array and then enable it with two methods that will be called on whenever we want to add an item to the queue using .add() and .remove() just so that we are clear what we are doing in our code.

Queue class

The constructor will be called automatically when we call the queue instance.

And that is it! It is pretty simple and a simple way to try to understand javascript classes as well.