Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to create a queue, then enqueue and dequeue elements in JavaScript

1 Answer

0 votes
class Queue {
    constructor() {
        this.items = []; // Array to store queue elements
    }

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

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

    // Peek: View the front element without removing it
    peek() {
        if (this.isEmpty()) {
            console.log("Queue is empty, nothing to peek");
            return null;
        }
        return this.items[0];
    }

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

    // Get the size of the queue
    size() {
        return this.items.length;
    }

    // Print the queue elements
    printQueue() {
        console.log("Queue contents:", this.items.join(", "));
    }
}

const queue = new Queue();

// Enqueue elements
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);

// Print the queue
queue.printQueue(); // Output: Queue contents: 10, 20, 30

// Peek at the front element
console.log("Front element:", queue.peek()); // Output: Front element: 10

// Dequeue elements
queue.dequeue(); // Output: 10 removed from the queue
queue.dequeue(); // Output: 20 removed from the queue

// Check if the queue is empty
console.log("Is queue empty?", queue.isEmpty()); // Output: Is queue empty? false

// Print the queue again
queue.printQueue(); // Output: Queue contents: 30



/*
run:

10 added to the queue
20 added to the queue
30 added to the queue
40 added to the queue
Queue contents: 10, 20, 30, 40
Front element: 10
10 removed from the queue
20 removed from the queue
Is queue empty? false
Queue contents: 30, 40

*/

 



answered Aug 22, 2025 by avibootz
...