Clearing the set using Javascript

In JavaScript, the clear() method removes all elements from a Set. For built-in Sets, you can use the native clear() method. For custom Set implementations, you reassign the container to an empty object.

Using Built-in Set clear() Method

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(5);

console.log("Before clear:", mySet);
mySet.clear();
console.log("After clear:", mySet);
console.log("Size:", mySet.size);
Before clear: Set(3) { 1, 2, 5 }
After clear: Set(0) {}
Size: 0

Custom Set Implementation

For a custom Set class, the clear method reassigns the container to a new empty object:

class MySet {
    constructor() {
        this.container = {};
    }
    
    add(element) {
        this.container[element] = element;
    }
    
    clear() {
        this.container = {};
    }
    
    display() {
        console.log(this.container);
    }
    
    size() {
        return Object.keys(this.container).length;
    }
}

const testSet = new MySet();

testSet.add(1);
testSet.add(2);
testSet.add(5);

console.log("Before clear:");
testSet.display();
console.log("Size:", testSet.size());

testSet.clear();

console.log("After clear:");
testSet.display();
console.log("Size:", testSet.size());
Before clear:
{ '1': 1, '2': 2, '5': 5 }
Size: 3
After clear:
{ }
Size: 0

Comparison

Method Use Case Performance
Built-in Set.clear() Standard JavaScript Sets Optimized by engine
Custom clear() Custom Set implementations Fast object reassignment

Conclusion

Use the native clear() method for built-in Sets. For custom implementations, reassigning the container to an empty object effectively clears all elements and resets the Set.

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

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements