Queues

Queue is a FIFO data structure. In this lesson, we look at Queues and how can they be implemented in Javascript.

Introduction

A queue is a linear collection where items are inserted at the end and are removed from the front. Hence queue is a FIFO (first-in first-out) data structure. It supports three basic operations: Insert and Remove.

  1. Inserting into the queue is called Enqueue.
  2. Extracting from the queue is called Dequeue.
  3. Look at the top element in the queue (the one that will be removed on Dequeue). It is called Peek.

Queue is an abstraction of the behavior that is very common in our daily lives e.g. drive through of a Coffee Shop. It helps process requests or tasks in the order that they arrive. Here's a quick animation on how queue works.

Queue is often compared and studied along with Stack which is a LIFO data structure.

Queue Implementation

We'll implement the Queue data structure using the following object:

Press + to interact
function Queue() {
this._head = 0;
this._data = [];
}
We are going to store the queue items in an array. 

  • data contains the items in the queue. At every enqueue, we push the new item into this array.
  • head is the index of the top or head of the queue. At every dequeue, we return the element pointed by the head and then increment the head to point to the next item.

Let's look at the code for Enqueue and Dequeue below:

...