JavaScript | weakMap.set() with Examples

The weakMap.set() is an inbuilt function in JavaScript which is used to set a new element with a particular key and value to a WeakMap object.
Syntax:

weakMap.set(key, value);

Parameters: It takes parameters “key” which is the key of the element which is to set to the WeakMap object and parameter “value” is the value of the element to set to the WeakMap object.
Return value: It returns the WeakMap object.

JavaScript code to show the working of this function:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script> 
  
    // creating WeakMap() object
    const weakmap1 = new WeakMap();
      
    // Creating some keys
    const key1 = {};
    const key2 = {};
  
    // Setting key and value to the object.
    weakmap1.set(key1, 'GeeksForGeeks');
    weakmap1.set(key2, 'gfg');
  
   // Returning the set values
   document.write(weakmap1.get(key1) +"<br>");
   document.write(weakmap1.get(key2));
  
</script>

chevron_right


Output:



GeeksForGeeks
gfg

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script> 
  
    // creating WeakMap() object
    const weakmap1 = new WeakMap();
      
    // Creating some keys
    const key1 = {};
    const key2 = {};
    const key3 = {};
    const key4 = {};
    const key5 = {};
    const key6 = {};
  
    // Setting key and value to the object.
    weakmap1.set(key1, 'GeeksForGeeks');
    weakmap1.set(key2, 'gfg');
    weakmap1.set(key3, 'GfG is a cse portal');
    weakmap1.set(key4, '12345');
    weakmap1.set(key5, '@#$%');
    weakmap1.set(key6, '1.34');
  
   // Returning the set values
   document.write(weakmap1.get(key1) +"<br>");
   document.write(weakmap1.get(key2) +"<br>");
   document.write(weakmap1.get(key3) +"<br>");
   document.write(weakmap1.get(key4) +"<br>");
   document.write(weakmap1.get(key5) +"<br>");
   document.write(weakmap1.get(key6));
  
</script>

chevron_right


Output:

GeeksForGeeks
gfg
GfG is a cse portal
12345
@#$%
1.34


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.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.