Does JavaScript Have a Queue Data Structure?


Larry Thompson

JavaScript does not have a built-in Queue data structure, but it can be easily implemented using arrays. In this tutorial, we will explore how to create a Queue in JavaScript and understand its basic operations.

What is a Queue?

A queue is an ordered collection of elements that supports two main operations: enqueue and dequeue. The enqueue operation adds an element to the end of the queue, while the dequeue operation removes and returns the element from the front of the queue. This follows the First-In-First-Out (FIFO) principle, similar to waiting in line at a store.

Implementing a Queue in JavaScript

To implement a Queue in JavaScript, we can make use of arrays due to their dynamic nature. Arrays provide methods like push() and shift(), which can be used to emulate enqueue and dequeue operations respectively.

We begin by creating an empty array that will serve as our queue:

let queue = [];

The Enqueue Operation

To add an element to the end of the queue, we can use the push() method:


Note: The element parameter represents the value you want to enqueue into the queue.

The Dequeue Operation

To remove and return the element from the front of the queue, we can use the shift() method:

let removedElement = queue.shift();

The shift() method not only removes but also returns the removed element so that you can store it in a variable for further use.

Checking if a Queue is Empty

In some scenarios, it might be necessary to check if a queue is empty before performing any operations. We can use the length property to check the size of the queue:

if (queue.length === 0) {
  console.log("Queue is empty");

Example Usage

Let’s see a simple example that demonstrates the usage of a queue:

let queue = [];

// Enqueue elements

// Dequeue an element
let removedElement = queue.shift();
console.log(removedElement); // Output: A

console.log(queue); // Output: ["B", "C"]


In conclusion, JavaScript does not have a built-in Queue data structure, but we can easily implement one using arrays and their push() and shift() methods. Queues are useful in scenarios where elements need to be processed in a specific order, following the First-In-First-Out (FIFO) principle.

By understanding how queues work and how to implement them, you can enhance your JavaScript programs by incorporating this essential data structure.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy