In this tutorial, you will learn about the queue data structure and how to implement a JavaScript queue using methods of the Array type.

Introduction to the Queue data structure

A queue is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue.

Unlike a stack, which works based on the last-in, first-out (LIFO) principle, a queue works based on the first-in, first-out (FIFO) principle.

A queue has two main operations involving inserting a new element and removing an existing element.

The insertion operation is called enqueue, and the removal operation is called dequeue. The enqueue operation inserts an element at the end of the queue, whereas the dequeue operation removes an element from the front of a queue.

The following figure illustrates a queue:

JavaScript Queue Illustration

Another important operation of a queue is getting the element at the front called peek. Different from the dequeue operation, the peek operation just returns the element at the front without modifying the queue.

The name queue comes from the analogy to a queue of customers at a bank. The customer who comes first will be served first, and the one who comes later is queued at the end of the queue and will be served later.

queue at a bank

Implementing a JavaScript queue using an array

You can use an array as a queue by using two methods of the Array type:

  • Add an element at the end of the array using the push() method. This method is equivalent to the enqueue operation.
  • Remove an element from the front of an array using the shift() method. It is the same as the dequeue operation.

Let’s implement a JavaScript queue data structure by using an array.

#javascript #programming #developer #web-development

JavaScript Array Tutorial - JavaScript Queue
2.35 GEEK