DEV Community

Cover image for Implement Queue using Array - Object oriented JavaScript
kapeel kokane
kapeel kokane

Posted on

Implement Queue using Array - Object oriented JavaScript

👋🏾 Hey There!

In today's post, we look into how we can implement a queue using just an Array in JavaScript.


If you end up liking this post, feel free to follow me on 🐦twitter where I post JavaScript tips for the visual learner like this one:

So let's begin 👐🏽

The lesser-known Array methods

Most developers know about the JavaScript Array methods like push() or pop() but are not aware about the lesser known methods: shift() and unshift().

While push and pop work at the rear end of the Array, shift and unshift work at the front.

Array methods

You see where I am going with this, we can treat the native JavaScript Array as a queue or a stack based on the methods that we chose to use. But in this method, we are going to do it the object-oriented way!

The Queue class

We will be creating a Queue class definition. As a part of that definition, we will be emulating the enque() and deque() methods.

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

  enque(num) {
    this._arr.push(num);
  }

  deque() {
    return this._arr.shift();
  }
}
Enter fullscreen mode Exit fullscreen mode

In the above class, we are using an internal _arr array that is not exposed to the external world outside the Queue. The only ways to interact with the array are the enque and deque methods!

If we look at how the methods are implemented, we are just treating the array as a queue, using the push() method to add to the queue and the shift() method to remove from the opposite end.

Using the Queue class

The Queue class that we created can be used as follows:

let que = new Queue();
que.enque(2);
que.enque(5);
que.enque(6);
que.enque(10);

que.deque(); // returns 2
que.deque(); // returns 5

// 6 and 10 are still in the queue
Enter fullscreen mode Exit fullscreen mode

And that's all, we've successfully implemented a queue data structure using a JavaScript Array and some object oriented Javascript.


Top comments (0)