Creating a Set using Javascript

In JavaScript, a Set is a collection of unique values. You can create sets using the native ES6 Set class or implement a custom set class. Let's explore both approaches.

Creating Sets with ES6 Set Class

The simplest way to create a set is using the built-in Set constructor:

// Create empty set
const set1 = new Set();

// Create set with initial values
const set2 = new Set([1, 2, 5, 6]);

console.log(set1);
console.log(set2);
Set(0) {}
Set(4) { 1, 2, 5, 6 }

Custom Set Implementation

You can also create a custom MySet class to understand how sets work internally:

class MySet {
    constructor() {
        this.container = {};
    }
    
    display() {
        console.log(this.container);
    }
    
    has(val) {
        return this.container.hasOwnProperty(val);
    }
    
    add(val) {
        this.container[val] = true;
        return this;
    }
}

// Test the custom set
const mySet = new MySet();
mySet.add(1).add(2).add(5);
mySet.display();
console.log(mySet.has(2));
{ '1': true, '2': true, '5': true }
true

Checking for Membership

The has() method checks if a value exists in the set:

const testSet = new Set([1, 2, 5, 6]);

console.log(testSet.has(5));   // Check if 5 exists
console.log(testSet.has(20));  // Check if 20 exists  
console.log(testSet.has(1));   // Check if 1 exists
true
false
true

Adding and Removing Elements

const mySet = new Set();

// Add elements
mySet.add(10);
mySet.add(20);
mySet.add(10); // Duplicate - won't be added

console.log(mySet);

// Remove element
mySet.delete(20);
console.log(mySet);

// Clear all elements
mySet.clear();
console.log(mySet);
Set(2) { 10, 20 }
Set(1) { 10 }
Set(0) {}

Conclusion

JavaScript Sets provide an efficient way to store unique values. Use the native Set class for most applications, but understanding custom implementations helps grasp the underlying concepts.

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

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements