The Little Guide of Queue in JavaScript by@germancutraro
31,652 reads

The Little Guide of Queue in JavaScript

Read on Terminal Reader

Too Long; Didn't Read

featured image - The Little Guide of Queue in JavaScript
Germán Cutraro HackerNoon profile picture


Germán Cutraro
react to story with heart


A queue is a simple data structure that allows elements to be inserted from one end, called the rear (also called tail), and deleted from the other end, called the front (also called head).

This behavior is called FIFO (First in First Out).


So, a queue is a linear data structure. A very important concept is that a queue deletes only the oldest added element.


The person that is removed was the first in the queue


  • Queues are used whenever we need to manage objects in order starting with the first one in.
  • Scenarios include printing documents on a printer, call center systems answering people on hold people, and so on.


  • A queue can be implemented using an array or a linked list.

So, in JavaScript doing a Queue is very simple because we can take arrays methods, like unshift and pop.

Remember :

unshift Adds a element to the beginning of the array.pop Deletes the last element of the array.


So the first thing that we are going to do is create a Queue constructor function with a empty array inside.

function Queue() { = [];}

Remember that we use the this keyword there because we need to pointer the object that we create.


The main methods will be add and remove:

Queue.prototype.add = function(record) {;}

Queue.prototype.remove = function() {;}

And we are going to add 3 methods more:

Queue.prototype.first = function() {return[0];}

Queue.prototype.last = function() {return[ - 1];}

Queue.prototype.size = function() {return;}

So, let’s see what we get:

const q = new Queue():q.add(1);q.add(2);q.add(3);console.log(q);


So, the oldest one is the element with the value of 1 because we added it first.

If you don’t believe me, you can use our last method to see it:

console.log(q.first());// -> 3console.log(q.last());// -> 1

So if we use the remove method the element that will be deleted is the oldest so the 1 is out.



And we have the last method call size

console.log(q.size())// -> 2

Return ‘‘2’’ after we delete the last element.

Complete Code:;

You have my Github if you wanna follow me, i will appreciate a lot!

Thanks to SoloLearn a fantastic app!

Great courses to learn Data Structures and Algorithms: ◾ Learning Data Structures in JavaScript from Scratch ◾ The Coding Interview Bootcamp: Algorithms + Data Structures

Thank you 😊


. . . comments & more!
Hackernoon hq - po box 2206, edwards, colorado 81632, usa