• JavaScript Video Tutorials

JavaScript - Set() constructor



In JavaScript, the Set() constructor is used to create a new Set object, which is a collection of unique values. A Set in JavaScript is similar to arrays but with some distinct characteristics:

  • Unique Values − A Set can only contain unique values. If we try to add a value that already exists in the Set, it will be ignored.
  • Iterative Order − Unlike arrays, Sets do not maintain the order of elements based on insertion. However, the order of elements can be obtained through iteration.
  • Iterative Methods − Sets provide methods to iterate over their elements, such as forEach(), for...of loops, and the values(), keys(), and entries() methods.
  • Type Flexibility − A Set can contain values of any data type, including primitive types, objects, and even undefined or NaN values.

Syntax

Following is the syntax of JavaScript Set() constructor −

new Set(iterable)

Parameters

This method accepts an optional parameter. The same is described below −

iterable (optional) − An iterable object (such as an array) whose elements will be added to the set. Each element must be unique.

If we don't specify this parameter, or its value is null, the new Set will be empty.

Return value

The Set() constructor returns a new Set object.

Examples

Example 1

In the following example, we are creating a Set object using the Set() constructor. We passed an array with duplicate values to the Set() constructor. However, the Set object automatically eliminates duplicates, so "set" contains only unique values.

<html>
<body>
   <script>
      const set = new Set([1, 2, 3, 2, 1]);
      document.write(set); // Output: Set {1, 2, 3}
   </script>
</body>
</html>

As we can see in the output, it eliminates all the duplicate values and returns only distinct values.

Example 2

In this example, we are not providing any iterable object as a parameter. As a result, it returns an empty set object as a result −

<html>
<body>
   <script>
      const set = new Set();
      document.write(set); // Output: Set {}
   </script>
</body>
</html>

As we can see in the output, it returned an empty set object.

Example 3

Here, we are providing "null" as a parameter. As a result, it returns an empty set object as a result −

<html>
<body>
   <script>
      const set = new Set(null);
      document.write(set); // Output: Set {}
   </script>
</body>
</html>

As we can see in the output, it returned an empty set object.

Advertisements