• JavaScript Video Tutorials

JavaScript - Set.size Property



In JavaScript, the Set.size property returns the number of elements in a Set object.

A Set is a collection of unique values where each value may occur only once. The size property provides a way to specify the number of distinct (unique) elements present in the Set.

Syntax

Following is the syntax of JavaScript Set.size property −

mySet.size

Return value

This property will return the number of unique elements in a set.

Examples

Example 1

Following is the basic usage of JavaScript Set.size property.

<html>
<body>
   <script>
      const set = new Set([10, 20, 40, 60, 70]);
      document.write(set.size);
   </script>
</body>
</html>

It will return 5 as result.

Example 2

This method returns the size of unique elements in a set, ignoring the duplicates.

<html>
<body>
   <script>
      const set = new Set([10, 10, 20, 40, 60, 60]);
      document.write(set.size);
   </script>
</body>
</html>

As we can see in the output, it returned the size of unique elements, ignoring the duplicates.

Example 3

If we calculate the size of an empty set, it will return 0 as result.

<html>
<body>
   <script>
      const set = new Set([]);
      document.write(set.size);
   </script>
</body>
</html>

As we can see in the output below, it returned 0 as result.

Advertisements