JavaScript Code


JavaScript Set add()


Set add() method

Set add() method is used to add an element to the set.

mySet.add(value);
  • mySet is a set object.
  • add is method name.

The add() method returns the set object with the added value.

Examples

1. Add elements 'a', 'e', 'i', 'o', and 'u' to the vowels set.

const vowels = new Set();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
console.log([...vowels]);

2. Add an element that is already existing in the set.

const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
vowels.add('a');
console.log([...vowels]);

Since a set can contain only unique elements, the original set remains unchanged.


Copyright @2022