• JavaScript Video Tutorials

JavaScript - WeakSet has() Method



The JavaScript WeakSet has() method is used to check whether the specified element or object exists in this weakSet or not. It returns a boolean value 'true' if an object exists in this WeakSet, and 'false' otherwise, and it always returns false if the value is not an object or not a non-registered symbol.

The WeakSet in JavaScript is a collection that can only contain objects and non-registered symbols. They cannot store arbitrary values of any type as other collections can like sets.

Syntax

Following is the syntax of JavaScript String has() method −

has(value)

Parameter

This method accepts one parameter named 'value', which is described below −

  • value − The value needs to be checked for presence in this WeakSet.

Return value

This method returns 'true' if the value exists in this WeakSet; 'false' otherwise.

Examples

Example 1

If the specified value exists in this WeakSet, this method will return 'true'.

In the following example, we are using the JavaScript WeakSet has() method to check whether the object 'newObj = {}' exists in this WeakSet or not.

<html>
<head>
   <title>JavaScript WeakSet has() Method</title>
</head>
<body>
   <script>
      const Obj = new WeakSet();
      const newObj = {};
      document.write("Appending object to this WeakSet");
      Obj.add(newObj);
      let res = Obj.has(newObj);
      document.write("<br>Does object ", newObj, ' is exists in this WeakSet? ', res);  
   </script>    
</body>
</html>

Output

The above program returns the following statements −

Appending object to this WeakSet
Does object [object Object] is exists in this WeakSet? true

Example 2

If the specified value does not exists in this WeakSet, this method will return 'false'.

The following is another example of the JavaScript WeakeSet has() method. In this example, we are using this method to check whether the value 10 (which is not an object) exists in this WeakSet or not.

<html>
<head>
   <title>JavaScript WeakSet has() Method</title>
</head>
<body>
   <script>
      const Obj = new WeakSet();
      const num = 10;
      document.write("Value: ", num);
      try {
         Obj.add(num);
      } catch (error) {
         document.write("<br>", error);
      }
      document.write("<br>Does value ", num, " is exists in this WeakSet? ", Obj.has(num));  
   </script>    
</body>
</html>

Output

Value: 10
TypeError: Invalid value used in weak set
Does value 10 is exists in this WeakSet? false
Advertisements