Clearing the elements of the Queue in Javascript

We can clear all elements from a queue by reassigning the container to an empty array. This is the most efficient way to remove all queue elements at once.

Syntax

clear() {
    this.container = [];
}

Example

Here's a complete example showing how the clear method works with a queue implementation:

class Queue {
    constructor(maxSize = 10) {
        this.container = [];
        this.maxSize = maxSize;
    }
    
    enqueue(element) {
        if (this.container.length < this.maxSize) {
            this.container.push(element);
        }
    }
    
    display() {
        console.log(this.container);
    }
    
    clear() {
        this.container = [];
    }
}

let q = new Queue(2);
q.enqueue(3);
q.enqueue(4);
console.log("Before clearing:");
q.display();

q.clear();
console.log("After clearing:");
q.display();

Output

Before clearing:
[ 3, 4 ]
After clearing:
[ ]

How It Works

The clear method works by:

  • Reassigning the container array to a new empty array []
  • This removes all references to existing elements
  • JavaScript's garbage collector automatically frees the memory of unreferenced elements

Alternative Approach

You can also clear a queue by setting its length to zero:

class Queue {
    constructor() {
        this.container = [];
    }
    
    clear() {
        this.container.length = 0;  // Alternative method
    }
    
    enqueue(element) {
        this.container.push(element);
    }
    
    display() {
        console.log(this.container);
    }
}

let queue = new Queue();
queue.enqueue("A");
queue.enqueue("B");
console.log("Before:");
queue.display();

queue.clear();
console.log("After:");
queue.display();
Before:
[ 'A', 'B' ]
After:
[ ]

Conclusion

Clearing a queue is simple with this.container = [] or this.container.length = 0. Both methods effectively remove all elements and reset the queue to its initial empty state.

Updated on: 2026-03-15T23:18:59+05:30

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements