Open In App

What is the use of the Add method in Sets in JavaScript ?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the add() method is used with Sets to add a new element to the Set. It ensures that the element is unique within the Set, meaning that duplicates are automatically ignored.

Example: Here, the add() method is used to add the values 1, 2, and 3 to the Set mySet. When the value 1 is added a second time, the Set automatically handles it, and no duplicate is added.

Javascript




let mySet = new Set();
 
mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // This won't result in a duplicate value
 
console.log(mySet); // Output: Set { 1, 2, 3 }


Output

Set(3) { 1, 2, 3 }

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads