The Javascript Queue

soham chakraborty
codeburst
Published in
2 min readMar 19, 2019

--

Graphical Representation of a Queue

In computer science, data structures are ways of organizing data with optimal ‘runtime complexity’ for adding or removing records. Javascript implements several data structures. Yet, software engineering interviewers ask about implementing some lower level data structures. We will code out one such ‘inferior’ data structure in javascript today — the ‘queue’.

What is this Queue?

The queue data structure is a container of sorts where records can enter into a container from one end and leave from the other end. The order in which the records enter the queue is the order they can come out. An important example of a queue in computer science occurs in a time-sharing system, in which programs with the same priority form a queue while waiting to be executed. In javascript, we wouldn’t need a queue since a javascript array can execute all the queue operations and much much more. Still, we would still need to know how to program a queue, especially before software engineering interviews.

Coding a Queue

So, what are the three methods that we would implement with a queue? We should be able to —

  1. add (enqueue) an element into a queue,

2. remove (dequeue) it from the queue,

3. and peek into the element that would be removed if the remove method is called on the queue.

The Javascript Array gives us such a variety of functionality that we can use some of its’ methods to our advantage while creating the queue methods. We will be using the ‘unshift’ and ‘pop’ methods while implementing the queue class. So, here we go.

class Queue {
constructor() {
this.records = [];
}

enqueue(record) {
this.records.unshift(record);
}

dequeue() {
return this.records.pop();
}

peek() {
return this.records[this.records.length-1];
}

print() {
console.log('The queue records are -', this.records);
}
}

Now that we have our queue class implemented, we can use this class to demonstrate the various queue operations.

const q = new Queue();
q.enqueue(1);
q.enqueue('abc');
q.enqueue(2)
q.enqueue('def');
q.print();
console.log('The next record to be removed is - ', q.peek());
q.dequeue();
q.dequeue();
q.print();

And here is the console output -

The above console output shows that the first record that we inserted into the queue is the first one that we removed.

P.S. If you liked my article please follow me on medium or twitter for other exciting articles on javascript and web development.

--

--