Skip to content
Related Articles

Related Articles

Improve Article

JavaScript weakMap.set() Method

  • Last Updated : 18 Sep, 2020

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

  • Example:




    <script> 
        function gfg() { 
        const weakmap1 = new WeakMap();
      
        const key1 = {};
        const key2 = {};
        const key3 = {};
      
        weakmap1.set(key1, 'G');
        weakmap1.set(key2, 'F');
        weakmap1.set(key3, 'G');
      
       document.write(weakmap1.get(key1) 
                     +weakmap1.get(key2)
                     +weakmap1.get(key3));
        
        gfg(); 
    </script> 
  • Output:
    GFG

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.



Example:

Input: weakmap1.get(key1)
Output: GeeksForGeeks

JavaScript code to show the working of this function:
Code #1:




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

Output:

GeeksForGeeks
gfg

Code #2:




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

Output:

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

Supported Browsers:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :