Tutorialspoint.dev

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:

<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


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter