• JavaScript Video Tutorials

JavaScript - Set.has() Method



The Set.has() method in JavaScript is used to verify whether a particular element exists in a set. It returns a Boolean value as a result, indicating whether the specified element is present in the Set or not.

Syntax

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

has(value)

Parameters

This method accepts only one parameter. The same is described below −

  • value − The element to check for in the set.

Return value

This method returns a Boolean value as result.

Examples of JavaScript Set.has() Method

Following are demonstrates the basic usage of Set.has() method −

Examples

Example 1

In the following example, we are searching whether the element "3" exists in this set or not, using the JavaScript Set.has() method −

<html>
<body>
   <script>
      const mySet = new Set([1, 2, 3, 4, 5]);
      const result = mySet.has(3);
      document.write(result);
   </script>
</body>
</html>

It returns "true" because the element "3" is present in the set.

Example 2

Here, we are searching for an element "kiwi" which is not present in the set −

<html>
<body>
   <script>
      const mySet = new Set(['Apple', 'Orange', 'Banana']);
      const result = mySet.has('Kiwi');
      document.write(result);
   </script>
</body>
</html>

It returns "false" because the element "Kiwi" is present in the set.

Example 3

In this example, we are checking whether the element "Tutorialspoint is present in an empty set −

<html>
<body>
   <script>
      const mySet = new Set();
      const result = mySet.has('Tutorialspoint');
      document.write(result);
   </script>
</body>
</html>

If we execute the above program, it returns "false" as result.

Advertisements