What is the use of the Add method in Sets in JavaScript ?
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 }
Contact Us