JavaScript | weakMap.get()

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.

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

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

42

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

undefined

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.