Queue | Javascript | Part-2

Praveen Mistry
2 min readSep 10, 2022

--

Introduction article to the data structure. Queue concept with practical examples applied to the Javascript language.

Are you looking to improve your fundamental knowledge of computer science, especially data structure and algorithms? Then you’re in the right place. Let’s go through some common data structures and implement them in JavaScript.

The queue is similar to a stack. The only difference is that the queue uses the FIFO principle (first in, first out). In other words, when you queue for the bus, the first in the queue will always board first.

To understand this, In the above picture, people make a queue to wait for the ride. The logic here is that if you get the queue first, you’ll be the first to be served. If you get there first, you’ll be the first out. FIFO.

Some examples of queue usage are:

  • Background tasks.
  • Printing/task processing.

QUEUE METHODS IN JAVASCRIPT

  • enqueue: Enter queue, add an element at the end.
  • dequeue: Leave the queue, remove the front element, and return it.
  • front: Get the first element.
  • isEmpty: Determine whether the queue is empty.
  • size: Get the number of the element(s) in the queue.

Same as with queues, there’s more than one way to implement a stack. But probably the simplest is using an array with its push and shift methods.

If we only use push and shift for adding and deleting elements, we’ll always follow the FIFO pattern and so operate over it like a queue.

Array in JavaScript has some attributes of the queue, so we can use an array to construct an example for the queue:

The big O of queue methods is the following:

  • Insertion — O(1)
  • Removal — O(1)
  • Searching — O(n)
  • Access — O(n)

Some Leetcode questions can be solved using a queue. Please have a look so you have a clear picture on your mind about queue data structure.

I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find more Leetcode solutions on my blog and my GitHub repository. Suppose you like what you learn. feel free to fork 🔪 and star ⭐ it.

In this blog, I have tried to collect & present the most important points to consider when building Javascript / Node.js applications, feel free to add, edit, comment, or ask.
I recommend you to go over the references for more details.
Happy coding!

--

--