A Simple Queue With Arrays

JavaScript

Data Structures

A Queue is a particular kind of abstract data type (ADT) or collection where entities are kept in order. You can only add new entities to the end of the list (enqueue) and only remove entities from the start of the list (dequeue). This is what makes a Queue a FIFO data structure (see further down).

When are queues useful?

Queues are mainly used to provide the service of storing and holding entities which are to be processed later.

Similarities with Stacks

Stacks and Queues have a lot of things in common. Thet are both linear data structures (elements are in sequence or a linear list) that both have flexible sizes, meaning that you don't have to allocate fixed size when initiating them.

LIFO

The main difference between a Queue and a Stack comes when you remove items. A Stack is a LIFO data structure, meaning "Last In First Out", it's much like an actual stack of plates. Imagine that you're stacking a bunch of plates on a table to build a tower. The last plate you put on that stack will be the first one you remove.

FIFO

The Queue however is a FIFO data structure, meaning "First In First Out". For this example, imagine that you're at the movie theatre, waiting in line to get in. When they open the doors, they don't let in the person who just arrived, instead, they let in the very first person who arrived.

Simple Queue implementation

The simplest ways to implement a Queue in JavaScript is to use the features of the built in Array.

SimpleQueue.dequeue()

Removing things from the Queue is really simple too. Since a Queue is a FIFO data structure we will only remove the first element in the queue every time, so we can use the built in Array.shift() method.

SimpleQueue.peek()

Peek is the method that we will use when we want to pull out the first element in the Queue to perform an action on it. If it succeeds we can dequeue it, if our action fails the element is still in the Queue. So it should just return the first item, nothing more.

Well, we could use some of the knowledge we gained from building a Linked List to replace the JavaScript Array with a Linked List instead, combined with some general improvements, to create a Queue that could be implemented in any language with the same principles. So let's do that!