DEV Community

Cover image for How to create a Queue  using javascript
Juan Restrepo
Juan Restrepo

Posted on

How to create a Queue using javascript

JavaScript comes with some out of the box data structures. This includes Arrays and objects. Linked List, graphs, trees, queues, and stacks are not included with JavaScript. These data structures need to be constructed using a class. The data structures mention are important to know since different data structures excel at storing and retrieving data more efficiently than others depending on the scenario. Today we will be covering how to make a Queue.

What is a Queue?

Alt Text
A queue is a data structure that follows a simple rule. first-in, first-out, or FIFO. You can think of the queue as a line to the movies. The first person in line will buy the tickets first and get out of the line.

Alt Text
A common use for this data structure is breadth first search. Breadth first search allows us to traverse a tree data structure by finding the shortest path.

What does a Stack Contain and how to build it?

class Queue{
    constructor(){
        this.data = []
    }
}
Enter fullscreen mode Exit fullscreen mode

To get started building a queue we need to create a queue class and inside the constructor, the object will be initialized with an empty array( this.data );

Enqueue

    enqueue(value){
        this.data.push(value)
        return this; 
    }
Enter fullscreen mode Exit fullscreen mode

The first instance method that will be covered is enqueue. Enqueue takes in a value as a parameter. Enqueue add items to the end of the array using push. Finally, return the instance of the class.

Dequeue

    dequeue(){
        // Linked list would be more ideal here since shift in an array is an O(N) time complexity 
        const removedValue = this.data.shift();
        return removedValue; 
    }
Enter fullscreen mode Exit fullscreen mode

The instance method dequeue removes values from the beginning of the array. We will be using array building methods to remove a value from the end of the array. The shift() method will be used. Finally, the removed value is returned

Peek

    peek(){
        return this.data[0];
    }
Enter fullscreen mode Exit fullscreen mode

The instance method peeks () returns the first value of an array

Empty

    empty(){
        return this.data.length === 0;
    }
Enter fullscreen mode Exit fullscreen mode

Finally, the empty() instance method just returns true if there are any values in the stack or false if the stack is empty.

Queues are very simple to build using array methods and are used for traversing trees and graphs. I hope this gave you a bit of insight into what queues are and what they are used for.

Top comments (0)