The JavaScript WeakMap set() method is used to add or modify the key-value pairs to the WeakMap object. The key must be unique.
Syntax:
WeakMapObj.set(key,value)
Parameters:
key: It represents the key of the element to be added or modified.
value: It represents the value of the element to be added or modified.
Returns:
Updated WeakMap object.
Example 1:
<!DOCTYPE html> <html> <body> <script> var hello = new WeakMap(); var obj = {}; hello.set(obj, 'HELLO'); document.writeln(hello.get(obj)); </script> </body> </html>
Example 2:
<!DOCTYPE html> <html> <body> <script type="text/javascript"> const testWeakmap = new WeakMap(); const object1 = {}; const object2 = {}; testWeakmap.set(object1, 'w3schools'); testWeakmap.set(object2, 'jai'); document.write(testWeakmap.get(object1)); document.write("</br>"); document.write(testWeakmap.get(object2)); </script> </body> </html>