• JavaScript Video Tutorials

JavaScript - Set.add() Method



The Set.add() method in JavaScript is used to add new element to a Set object. Sets are collections of unique values, i.e. each element must be unique. If we try to add an element with the same value already in this set, it ignores the duplicate values and maintains the uniqueness.

Syntax

Following is the syntax of JavaScript Set.add() method −

add(value)

Parameters

This method accepts the following parameter −

  • value −The value to be added to the Set.

Return value

This method returns the Set object itself with the added values.

Examples

Example 1

In the following example, we are using the JavaScript Set.add() method to insert the numbers 5 and 10 to the "numberset" set −

<html>
<body>
   <script>
      const numberSet = new Set();
      numberSet.add(5);
      numberSet.add(10);
      document.write(`Result: ${[...numberSet]}`);
   </script>
</body>
</html>

If we execute the above program, the provided integer elements will be added to the set.

Example 2

If we pass a new element with the same value already in this set, it ignores the duplicate values −

<html>
<body>
   <script>
      const numberSet = new Set();
      numberSet.add(5);
      numberSet.add(5);
      numberSet.add(5);
      numberSet.add(10);
      document.write(`Result: ${[...numberSet]}`);
   </script>
</body>
</html>

As we can see in the output, duplicate values are ignored and the set maintains uniqueness.

Example 3

In this example, we are inserting string elements to the "stringSet" set −

<html>
<body>
   <script>
      const stringSet = new Set();
      stringSet.add("Tutorialspoint");
      stringSet.add("Tutorix");
      document.write(`Result: ${[...stringSet]}`);
   </script>
</body>
</html>

After executing the above program, the provided string elements will be added to the set.

Example 4

In this example, we are adding two objects to the "objectSet" set using the add() method −

<html>
<body>
   <script>
      const objectSet = new Set();
      const obj1 = { Firstname: "Joe" };
      const obj2 = { Lastname: "Goldberg" };
      objectSet.add(obj1).add(obj2);
      
      document.write(`Result: ${JSON.stringify([...objectSet])}`);
   </script>
</body>
</html>

As we can see in the output, object values have been added to the set.

Example 5

The following example inserts the the boolean values true and false to the "booleanSet" set −

<html>
<body>
   <script>
      const booleanSet = new Set();
      booleanSet.add(true);
      booleanSet.add(false);
      document.write(`Result: ${[...booleanSet]}`);
   </script>
</body>
</html>

After executing the program, the set contains "true" and "false" as elements.

Advertisements