The add() method of the Set object in JavaScript inserts a new element with a specified value into a Set object, if there isn't an element with the same value already in the Set.
The syntax of Set.add() method is:
add(value)
This add() method of Set inserts a new element with a specified value into a Set object, if there isn't an element with the same value already in the Set.
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value of the element to add to the Set. |
Set.add() returns value of type Set
.
In JavaScript, we can use the add()
method to add a number to a Set object.
For example,
numbers
.add()
method to add the number 5 to the numbers
Set.numbers
Set to the console using console.log()
.const numbers = new Set();
numbers.add(5);
console.log(numbers);
Set { 5 }
In JavaScript, we can use the add()
method to add a string to a Set object.
For example,
fruits
.add()
method to add the string 'apple' to the fruits
Set.fruits
Set to the console using console.log()
.const fruits = new Set();
fruits.add('apple');
console.log(fruits);
Set { 'apple' }
In JavaScript, we can use the add()
method to add an object to a Set object.
For example,
people
.add()
method to add an object representing a person to the people
Set.people
Set to the console using console.log()
.const people = new Set();
const person = { name: 'John', age: 30 };
people.add(person);
console.log(people);
Set { { name: 'John', age: 30 } }
In this JavaScript tutorial, we learned about add() method of Set: the syntax and few working examples with output and detailed explanation for each example.