Understanding ‘Queue’ in JavaScript

Joan Yassi
Webtips

--

One way or another we have dealt with inventories before(even as simple as your snacks cupboard); And therefore applied the ‘First In, First Out’ concept. By eating the oldest box of chocolate first, and saving the new one with a longer expiry date on it, you were (consciously or not) managing your snack inventory using the FIFO concept.

How does it apply to Javascript?

Well, Javascript Queue uses the same principle (minus the expiring date) to handle data.

Queue is a data structure that allows data to be inserted from the ‘back’ (or tail), and be deleted from the ‘front’ (head).

Whether you choose to add the value from the left and extract them from the right or the other way around, does not really matter. Just make sure that you extract the oldest item of the array first. Let’s look at some examples.

Implementation

Let’s create an object to represent our Queue and give it few methods (add and remove):

In Javascript, push is a method that adds an element at the end of an array (index of array.length-1). shift is a method used to removed the first element of an array (at index of 0). And this is the behaviour we want to have: always extract the first (oldest) element that was added to the queue.

Let’s try our code by adding few values to our brand new queue, and print the result to the console. Keep track of the order of each value.

The console:

Now the whole point of this data structure is to be able to grab and use that value that we extract from the queue. In our example, ‘Javascript’ was the first element to be added to the queue. Therefore, it should be the first one to extract for our queue object to be any good.

So, let’s see what the remove method of our queueObject has to offer:

Checking the console:

As you can see, the oldest (first in…) element of the queue (‘Javascript’) was extracted (…first out) and stored inside the valueToBeUsed variable.

Stretch

In this example, we added items to the right (rear) and retrieved them to the left (front). It can also be done the other way around, the important notion is to always make sure that the first (oldest) item to be added to the queue must be retrieved first.

Below is an example of how to create a Queue from left (rear) to right (front).

Conclusion

There are many ways to generate and handle the Queue data structure in Javascript. This was just a simple option, thank you for reading and feel free to share how you approach this concept within your code.

--

--