DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

What is new Set() in javascript?

In JavaScript, Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. The Set object was introduced in ECMAScript 2015 (ES6) and provides a simple and efficient way to manage a collection of unique values.

Here's a brief explanation of Set:

  1. Unique Values:

    • A Set can only contain unique values. If you try to add a duplicate value, it won't be added, and the set will remain unchanged.
  2. Creation:

    • You can create a new Set using the new Set() constructor. You can also initialize a Set with an iterable, such as an array.
     const mySet = new Set();
    

    or

     const mySet = new Set([1, 2, 3, 4, 5]);
    
  3. Adding and Removing Elements:

    • You can add an element to a Set using the add method:
     mySet.add(6);
    
  • To remove an element, you can use the delete method:

     mySet.delete(3);
    
  1. Checking for Existence:

    • You can check if a value exists in a Set using the has method:
     console.log(mySet.has(3)); // Returns false after deleting 3
    
  2. Size:

    • The size property returns the number of elements in a Set:
     console.log(mySet.size); // Returns the number of elements
    
  3. Iteration:

    • You can iterate through the elements of a Set using methods like forEach or the for...of loop:
     mySet.forEach(value => {
       console.log(value);
     });
    

    or

     for (const value of mySet) {
       console.log(value);
     }
    
  4. Clearing the Set:

    • The clear method removes all elements from the Set:
     mySet.clear();
    

Set is particularly useful when you need to maintain a collection of unique values without duplicates. It provides a convenient and performant way to handle such scenarios.

Top comments (0)