Skip to content
Related Articles

Related Articles

Improve Article

JavaScript weakMap.get() Method

  • Last Updated : 18 Sep, 2020

Below is the example of weakMap.get()() method.

  • Example:




    <script> 
        function gfg() { 
      
    const weakmap1 = new WeakMap(); 
      
    const key1 = {}; 
      
    weakmap1.set(key1, 12); 
      
    document.write(weakmap1.get(key1)); 
        
        gfg(); 
    </script> 
  • Output:
    12

The weakMap.get() is an inbuilt function in JavaScript which is used to return a particular element from a object WeakMap.

Syntax:

weakMap.get(key);

Parameters: It accepts a parameter “key” which is the key of the element which is going to be returned from the object weakmap.

Return values: It returns the element which is associated with the particular key in the WeakMap object and it returns undefined if the key can not be found.



Example:

Input: weakmap1.get(key1)
Output: 42

JavaScript code to show the working of weakmap() function:
Code #1:




<script>
  
   // Creating a WeakMap() object
   const weakmap1 = new WeakMap();
     
   // Creating a key "key1"
   const key1 = {};
     
   // setting value 42 with key "key1" in the 
   // object weakMap
   weakmap1.set(key1, 42);
     
   // Getting the specified elements i.e, 42
   document.write(weakmap1.get(key1));
  
</script>

Output:

42

Code #2:




<script>
  
   // Creating a WeakMap() object
   const weakmap1 = new WeakMap();
     
   // Creating a key "key1"
   const key1 = {};
     
   // Getting the specified elements
   document.write(weakmap1.get(key1));
  
</script>

Output:

undefined

Here output is undefined because the key “key1” has not been set at the end of the weakMap object.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera



My Personal Notes arrow_drop_up
Recommended Articles
Page :