The Queue Data Structure in Javascript — Interview questions

Data structures are all about runtime complexity, so before reading this article, I suggest you read my previous blog on time runtime complexity and Big O notation, link.

What is Data Structures?

When it comes to answering this question, there are two big points we need to consider:

  1. JavaScript offer natively several implementations of data structures. However, we still need to understand the “low level” one to be able to succeed in an interview.

Difference between an Array and a Queue

In the below image, I’m comparing what an array in JS is capable to do with what a queue can do.

What is a Queue?

A queue is like a container where data enter from one side and exit from the other side.


Queue implementation

Now that we know what a queue is and which method in JS can replicate the same behaviour, the rest is pretty straight forward. We are going to create a Class and initialize it with an empty array which is going to be our queue. In a classic Array we have different methods exposed to it such as shift, unshift, push, pop, splice and slice, but in this case, the only two methods that we are going to make accessible are unshift to add to the queue, and pop to remove.

The code

The first step is to create a class and initialize this class with an empty array

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store