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

ParameterOptional/RequiredDescription
valuerequiredThe 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,

  1. Create a new Set object numbers.
  2. Use the add() method to add the number 5 to the numbers Set.
  3. Log the numbers Set to the console using console.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,

  1. Create a new Set object fruits.
  2. Use the add() method to add the string 'apple' to the fruits Set.
  3. Log the fruits Set to the console using console.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,

  1. Create a new Set object people.
  2. Use the add() method to add an object representing a person to the people Set.
  3. Log the people Set to the console using console.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.