• JavaScript Video Tutorials

JavaScript - WeakMap get() Method



In JavaScript, the WeakMap.get() method is used to return a 'value' associated with a specified 'key' from a WeakMap.

This method accepts a 'key' as a parameter and checks if the key exists in the WeakMap. If found, it returns the value associated with it. If the key is not found, it returns 'undefined'.

This method is compatible on almost every browser such as Chrome, Edge, Firefox, Opera, and Safari.

Syntax

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

get(key)

Parameters

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

  • key − The key whose associated value we want to retrieve.

Return value

This method returns the value associated with a specified key, if the key is found in the WeakMap. Otherwise, it returns undefined.

Examples

Example 1

In the following example, we are adding two key-value pairs to a WeakMap object. Then we are retrieving the value associated with 'key1' and 'key2' using the JavaScript WeakMap.get() method.

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

If we execute the above program, it returns the values ('apple' and 'banana') associated with the specified keys ('key1' and 'key2').

Example 2

In this example, we are retrieving the value associated with 'key2', which is doesn't exist in the WeakMap object −

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

After executing the above program, the get() method returns undefined.

Example 3

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

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

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

Advertisements