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