• JavaScript Video Tutorials

JavaScript - WeakMap has() Method



In JavaScript, the WeakMap.has() method is used to verify whether an element with a specified key exists in the WeakMap object.

This method takes a "key" of the element as an argument to verify if it is present in the Map object and returns a Boolean value as a result. If the specified key is present in the Map, it returns "true". Otherwise, it returns "false".

The WeakMap.has() method still returns "true", if a key exists in the Map and if the corresponding value in the key-value pair is "undefined".

Syntax

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

has(key)

Parameters

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

  • key − The key to search for in the WeakMap.

Return value

This method returns Boolean value as a result.

Examples

Example 1

In the following example, we are checking whether an element with the specified key ('key1') exists in this WeakMap or not using JavaScript WeakMap.has() method −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key1 = {};
      let key2 = {};
      
      weakMap.set(key1, "apple");
      weakMap.set(key2, "banana");
      
      document.write(weakMap.has(key1));
   </script>
</body>
</html>

The above program returns "true" because the key "key1" is present in the WeakMap.

Example 2

Here, we are trying to check an element with a specified key 'key2' which is not present in the WeakMap object −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key1 = {};
      let key2 = {};
      
      weakMap.set(key1, "apple");
      
      document.write(weakMap.has(key2));
   </script>
</body>
</html>

The above program returns "false" because the key "key2" is not present in the WeakMap.

Example 3

In this example, the WeakMap has a key 'key1' with a value of 'undefined' −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key1 = {};
      let key2 = {};
      
      weakMap.set(key1, undefined);
      weakMap.set(key2, "banana");
      
      document.write(weakMap.has(key1));
   </script>
</body>
</html>

The above program returns true because 'key1' exists, even though its value is undefined.

Example 4

If the do not pass any argument to the get() method, it returns "false" as result −

<html>
<body>
   <script>
      let weakMap = new WeakMap();
      let key1 = {};
      let key2 = {};
      
      weakMap.set(key1, "apple");
      weakMap.set(key2, "banana");
      
      document.write(weakMap.has());
   </script>
</body>
</html>

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

Advertisements