JavaScript Set add()
Syntax & Examples
Set.add() method
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.
Syntax of Set.add()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value of the element to add to the Set. |
Return Type
Set.add() returns value of type Set
.
✐ Examples
1 Using add() to add a number to a Set
In JavaScript, we can use the add()
method to add a number to a Set object.
For example,
- Create a new Set object
numbers
. - Use the
add()
method to add the number 5 to thenumbers
Set. - Log the
numbers
Set to the console usingconsole.log()
.
JavaScript Program
const numbers = new Set();
numbers.add(5);
console.log(numbers);
Output
Set { 5 }
2 Using add() to add a string to a Set
In JavaScript, we can use the add()
method to add a string to a Set object.
For example,
- Create a new Set object
fruits
. - Use the
add()
method to add the string 'apple' to thefruits
Set. - Log the
fruits
Set to the console usingconsole.log()
.
JavaScript Program
const fruits = new Set();
fruits.add('apple');
console.log(fruits);
Output
Set { 'apple' }
3 Using add() to add an object to a Set
In JavaScript, we can use the add()
method to add an object to a Set object.
For example,
- Create a new Set object
people
. - Use the
add()
method to add an object representing a person to thepeople
Set. - Log the
people
Set to the console usingconsole.log()
.
JavaScript Program
const people = new Set();
const person = { name: 'John', age: 30 };
people.add(person);
console.log(people);
Output
Set { { name: 'John', age: 30 } }
Summary
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.