What is the use of the Add method in Sets in JavaScript ?
Last Updated :
01 Feb, 2024
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);
console.log(mySet);
|
Output
Set(3) { 1, 2, 3 }
Share your thoughts in the comments
Please Login to comment...