Creating a queue using Javascript arrays and classes.

Gage Thornberry
2 min readAug 7, 2020

Arrays are in my opinion the most dynamic data structure of them all. Arrays are particularly useful for holding multiple types of data inside of it.

Arrays hold objects, strings, booleans, and also have a ton of built in methods that can be used to iterate over arrays to pull out the data you want from it.

With great power comes great responsibility, and something you should consider when using arrays is what your runtime complexity might be.

Identifying your complexity is usually pretty straight forward. If you’re looping through an array with a length of the input size, you’re likely using linear complexity.

If you’re using a for loop inside of a for loop, you might be using quadratic complexity or n*n.

These looping array methods are nice to use but they’re the slowest of the array methods in JavaScript.

Methods like pop() unshift() and push() are less dynamic but very valuable in terms of speed.

It would be impossible to solve every problem using only these three methods, but something we can do with them is implement a queue using JavaScript classes.

Implementing a Queue -

So what is a queue?

A queue can be compared to standing in a line of people at a concession stand. You go to the back, wait your turn, and then get served in the same order as everybody else. This type of order follows the same rules as the First In First Out method, or FIFO for short.

We can use this methodology to create a queue using an array. We will add items to one side and pull items from the other, the same way you would a line of people.

The goal is we want to use a class so that we can hold our current queue in an array, and then create methods below it that would add and remove items from our current queue.

So what does this look like?

We’ve defined a class, created a queue array, and created our add and remove methods that would update the queue when called with queue.add(item) or queue.remove(item).

Be sure to remember to create the constructor so that you can access that queue data. Queue’s are pretty simple, but they’re surprisingly a lot faster than array looping methods.

This blog is a multi-part series that will be getting into stacks and using stacks to solve complex problems.

In the next blog we’ll be using classes to create stacks in JavaScript.

Thanks for reading!

--

--