JavaScript: Implement a Queue using Arrays / Objects

Introduction

A queue is a data structure that follows the FIFO (First In, First Out) principle. The first element added to the queue is the first one to be removed. A queue has two main operations:

  • Enqueue: Adds an element to the end of the queue.
  • Dequeue: Removes an element from the front of the queue.

This guide will walk you through writing a JavaScript program to implement a queue using arrays and objects.

Problem Statement

Create a JavaScript program that:

  • Implements a queue using both arrays and objects.
  • Allows operations like enqueue (add elements) and dequeue (remove elements).
  • Displays the elements in the queue after each operation.

Solution Steps

  1. Implement the Queue Using Arrays:
    • Use JavaScript's built-in array methods to add (push) and remove (shift) elements.
  2. Implement the Queue Using Objects:
    • Use an object to store elements and track the front and rear of the queue using indices.
  3. Display the Queue: Output the queue elements after each operation.

JavaScript Program

Method 1: Implementing a Queue Using Arrays

// JavaScript Program to Implement a Queue using Arrays
// Author: https://www.rameshfadatare.com/

class QueueArray {
    constructor() {
        this.queue = [];
    }

    // Enqueue: Add element to the end of the queue
    enqueue(element) {
        this.queue.push(element);
        console.log(`${element} added to the queue`);
    }

    // Dequeue: Remove element from the front of the queue
    dequeue() {
        if (this.isEmpty()) {
            console.log("Queue is empty");
            return null;
        }
        const removedElement = this.queue.shift();
        console.log(`${removedElement} removed from the queue`);
        return removedElement;
    }

    // Check if the queue is empty
    isEmpty() {
        return this.queue.length === 0;
    }

    // Display the queue elements
    displayQueue() {
        console.log("Queue:", this.queue);
    }
}

// Example usage
const queueArray = new QueueArray();
queueArray.enqueue(1);
queueArray.enqueue(2);
queueArray.enqueue(3);
queueArray.displayQueue();
queueArray.dequeue();
queueArray.displayQueue();

Output for Array Queue Example

1 added to the queue
2 added to the queue
3 added to the queue
Queue: [ 1, 2, 3 ]
1 removed from the queue
Queue: [ 2, 3 ]

Method 2: Implementing a Queue Using Objects

// JavaScript Program to Implement a Queue using Objects
// Author: https://www.rameshfadatare.com/

class QueueObject {
    constructor() {
        this.queue = {};
        this.front = 0;
        this.rear = 0;
    }

    // Enqueue: Add element to the end of the queue
    enqueue(element) {
        this.queue[this.rear] = element;
        this.rear++;
        console.log(`${element} added to the queue`);
    }

    // Dequeue: Remove element from the front of the queue
    dequeue() {
        if (this.isEmpty()) {
            console.log("Queue is empty");
            return null;
        }
        const removedElement = this.queue[this.front];
        delete this.queue[this.front];
        this.front++;
        console.log(`${removedElement} removed from the queue`);
        return removedElement;
    }

    // Check if the queue is empty
    isEmpty() {
        return this.rear === this.front;
    }

    // Display the queue elements
    displayQueue() {
        console.log("Queue:", this.queue);
    }
}

// Example usage
const queueObject = new QueueObject();
queueObject.enqueue(10);
queueObject.enqueue(20);
queueObject.enqueue(30);
queueObject.displayQueue();
queueObject.dequeue();
queueObject.displayQueue();

Output for Object Queue Example

10 added to the queue
20 added to the queue
30 added to the queue
Queue: { '0': 10, '1': 20, '2': 30 }
10 removed from the queue
Queue: { '1': 20, '2': 30 }

Explanation

Method 1: Queue Implementation Using Arrays

  • Enqueue: Adds an element to the end of the queue using the push() method.
  • Dequeue: Removes an element from the front of the queue using the shift() method, which also shifts all remaining elements forward.
  • isEmpty: Checks whether the queue is empty by comparing the length of the array to 0.
  • displayQueue: Prints the current elements of the queue.

Method 2: Queue Implementation Using Objects

  • Enqueue: Adds an element at the rear index and increments the rear counter.
  • Dequeue: Removes the element at the front index and increments the front counter. The element is removed by deleting the object property.
  • isEmpty: Checks if the front and rear indices are equal, which indicates that the queue is empty.
  • displayQueue: Prints the current state of the queue using an object, where each index is a key.

Conclusion

This JavaScript program demonstrates how to implement a queue using both arrays and objects. Both approaches allow for typical queue operations like enqueueing and dequeueing, but using an object can be more memory-efficient when working with large queues, as it doesn't require shifting all elements like arrays do. Understanding both methods gives insight into how different data structures can be implemented in JavaScript.

Comments