What is the use of weakSet.has() method in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

weakSet.has()

This is an inbuilt function in javascript which is used to return a boolean value on scrutinizing whether an object is present in weakSet or not. The weakSet object lets you store weakly held objects in a collection.

Syntax

weakSet.has(obj);

Arguments

From the above line of code, weakSet.has() accepts a parameter 'obj' and checks whether the parameter is present in the provided weakSet or not.

Returning value

Based on presence of value, whether it is in weakSet or not, the weakSet.has() method returns a boolean output. If the value is present then true will be returned else false will be returned.

Example-1

In the following example weakSet.has() checks whether the object(user provided) 'object1' is present in the weakSet or not. Since the object "object1" is present in the weakSet it returns true as the output. 

Live Demo

<html>
<body>
<script type="text/javascript">
   const object = new WeakSet();
   const newObj = {
      'prop': 1
   };
   object.add(newObj);
   document.write(object.has(newObj));  // returns true
</script>
</body>
</html>

Output

true

Example-2

In the following example weakSet.has() checks whether the object(user provided) 'object1' is present or not in the weakSet. Since the object is absent it returns false as the output. 

Live Demo

<html>
<body>
<script type="text/javascript">
   const object = new WeakSet();
   const newObj = {
      'prop1':1
   };
   document.write(object.has(newObj)); // returns false
</script>
</body>
</html>

Output

false
raja
Published on 24-Jun-2019 08:46:51
Advertisements