What Happens when you try to Add a Duplicate Value to a Set in JavaScript ?
Last Updated :
01 Feb, 2024
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);
console.log(mySet);
|
Output
Set(3) { 1, 2, 3 }
Share your thoughts in the comments
Please Login to comment...