JavaScript Data Structure Pt 3: Queue
Tags: javascript, beginners, tutorial, webdev
Published: 2023-02-19 22:31:39

## Table of contents 
  * [Introduction](#intro)
  * [Prerequisites](#pre)
  * [First-In, First-Out](#fifo)
  * [Queue Operations](#operations)
  * [Final Queue Structure](#final)
  * [Conclusion](#conclusion)
  * [Exercises](#exercises)

_____

## Introduction <a name="intro" />

In this tutorial, we will dive into the **Queue data structure**, and this is **part 3** of a follow-up tutorial from our ***JavaScript Data Structure series***. By the end of this tutorial, we will learn how to **explain**, **define**, and **use** a **Queue Data Structure** in **JavaScript**. We will assume you have some basic knowledge of **JavaScript** to follow along. 

---

## Prerequisites <a name="pre" />

- Basic JavaScript `syntax` and **concepts**
- Basic understanding of JavaScript `Arrays`
- Familiar with `this` **keyword**
- Familiar with `Class` **objects** and `Functions`

---

## First In, First Out <a name="fifo" />

The **Queue Data Structure** is a **linear data structure** where elements are **inserted** at the **end** of the `array` and **removed** at the **front** of the `array`, mainly known as **First-In**, **First-Out**, or **FIFO**. It benefits many everyday things that we might not have noticed initially. When we watch videos on **YouTube**, we tend to see a **playlist** of videos; after we watch the **first** video, the **following** video is already in **Queue**, ready to play after the end of the first video, and so on—one of many ways to utilize the **Queue Data Structure**.

![Queue Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0w7rrpylsnec7v4gaeka.png)

**Term:** Queue Data Structure
**Definition:** A data structure in which elements are organized in a linear order. Each element is inserted from the rear and removed from the front of the structure.  

- **Synonyms:** Arrays, Stack, Linked List, Queue
- **Acronyms:** FIFO

---

## Queue Operations <a name="operations" />

Now that we know what the Queue Data Structure can be helpful for. Let’s learn how to create it in JavaScript. There are a few operations that our Queue Structure should be able to handle. We will start with our `Queue Class` Object, where we store our operation `functions` and construct our `array`. We will initiate a JavaScript `class` named **Queue**

**Queue Class**

```jsx
 class Queue {}
```

1. Using the `class` keyword to create a unique **function** that will allow us to define our `functions` to work with `data` 

> [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) MDN
> 

---

**Array constructor**

The `class` object comes with built-in methods, the `constructor()` being one of the most commonly used to create an object instance of that class. 

```jsx
class Queue {
  constructor(){
    this.items = [];
  }
}
```

1. Using the `constructor` function, we create a new **instance** variable named `items` and assign it an empty `array` 
2. `this` keyword is a reference to our `items` object within our function

We can now call our Queue class using the `new` keyword, where it will automatically call the `constructor` and initiate our `items` variable, and assign an empty `array`. 

```jsx
let queue = new Queue()

console.log(queue.items) // []
```

1. Initiate a Queue class with the `new` keyword
2. Log out our `items` property from our new `queue`

> [Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) MDN
> 

> [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) MDN
> 

> [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) MDN
> 

---

**Enqueue function**

The purpose of our `Queue` is to **add** `elements` to the rear of our **structure**. We can use the **built-in** `push` **method** to insert an `element` to the end of our `items`. 

```jsx
enqueue(element){
  this.items.push(element);
}
```

1. The `element` inside our `parameters` will be the item we will pass into our function.
2. Using the `push()` method on our `items` will add the `element` to the end of the `items`. 

> [push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) MDN
> 

---

**Dequeue function**

Our Queue should be able to remove the first `element` of our `items` array. We can use the built-in shift method to accomplish this.

```jsx
dequeue(){
  return this.items.shift()
}
```

1. Using the `shift()` method will remove the first `element` in our `items` 

---

**Front function**

We need to be able to check what is about to be removed from the front of our structure too. We can quickly return the first element of our array by accessing the first element of our array. 

```jsx
front(){
  return this.items[0]
}
```

1. We can easily access the first `element` in our `items` array by using the `array indices` using brackets `[]` and the first integer of the `array`, which is `0`

> [Array indices](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices) MDN
> 

---

**Check Empty function**

Checking if we have an empty `items` array is also a nice feature to include. We can return a true or false result by checking the length of our `items`. If our `items` are strictly equal to zero, then it is `true`; otherwise `false`. 

```jsx
checkEmpty(){
  return this.items.length === 0;
}
```

1. Using the **strictly equals** `===` operation allows us to compare the size of our `items` with `0` easily, returning `true` or `false`

 

> [Strictly Equals ===](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) MDN
> 

---

### Print Queue

We need to see what our entire Queue structure looks like. Printing out our Queue. We can do so by iterating through our `array` and returning the `elements` in a string for readability. 

```jsx
printQueue(){
  let str = ""
	for(let i = 0; i < this.items.length; i++){
		str += this.items[i] + ", ";	
	}
	
	return str
}
```

1. Our function `printQueue()` 
2. `let str` an empty `string` where our `elements` will be added
3. `for loop` allows us to loop through an `array` where we can check the length of our `array` and iterate till we reach the end of the `array` 
4. In our `for loop` statement, we assign each `element` that is iterated and add a space for readability. 
5. Returning the final results from our `str` when the `for loop` is done iterating. 

> [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) MDN
> 

---

## Final Queue Structure <a name="final" />

```jsx
class Queue {
  constructor(){
    this.items = []
  }
  
  enqueue(element){
    this.items.push(element)
  }
  
  dequeue(){
    this.items.shift()
  }
  
  front(){
    return this.items[0]
  }
  
  checkEmpty(){
    return this.items.length === 0;
  }
  
  printQueue(){
    let str = "";
    for(let i = 0; i < this.items.length; i++){
      str += this.items[i] + ", "
    }
    return str
  }
  
}
```

Let us review what we have implemented. We have five functions needed for a FIFO structure or Queue Data Structure. Our enqueue function adds an element to the end of the Queue; the dequeue function removes the first element in the Queue; the front function returns the first item in the Queue; the check empty function returns true or false whether Queue is empty or not, last but not least the print queue function returns a string of our Queue for readability.

You can create a new queue and use its methods like so: 

```jsx
let queue = new Queue();

console.log(queue.isEmpty()); // true

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

console.log(queue.printQueue()); // 10 20 30
console.log(queue.front()); // 10
console.log(queue.dequeue()); // 10
console.log(queue.printQueue()); // 20 30
```

## **Conclusion** <a name="conclusion" />

In this article, we’ve covered the basics of a Queue Data Structure in JavaScript. We started by discussing the basics of FIFO, then we explored creating the structure's operations, to using our queue structure. 

In summary, JavaScript is a powerful tool for modern web development, and we hope this article has given you a solid foundation for exploring it further. Remember to keep learning, practicing, and experimenting, and you'll be well on your way to becoming a proficient JavaScript developer.

## **Exercises** <a name="exercises" />

1. Why and when should I use a Queue data structure instead of an Array?
2. What are some types of Queues?
3. Implement a Queue using two Stacks