What Happens when you try to Add a Duplicate Value to a Set in JavaScript ?

When you try to add a duplicate value to a Set in JavaScript using the add() method, the Set ignores the duplicate value. Sets are designed to store unique values only, and adding a value that is already present in the Set does not result in duplicates.

Example: Here, even though the value 1 is added to the Set twice, the Set only contains unique values. When you log the Set, you’ll see that it still contains only the values 1, 2, and 3.

Javascript




let mySet = new Set();
 
mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // Attempting to add a duplicate value
 
console.log(mySet); // Output: Set { 1, 2, 3 }


Output

Set(3) { 1, 2, 3 }


Contact Us