The set method of the JavaScript WeakMap is utilized to insert or modify an element within a WeakMap object by associating it with a specific key-value pair. It is essential that each value is linked to a distinct key, which must be an object.
Syntax
The syntax for the set method is depicted as follows:
weakMapObj.set(key,value)
Parameter
key - It represents the key to be added.
value - It represents the value to be added.
Return
The WeakMap object.
JavaScript WeakMap set method example
In this section, we will explore the set function by examining a variety of examples.
Example 1
Let’s examine an example of how to insert elements into a WeakMap object.
<script>
var wm = new WeakWeakMap();
var obj1 = {};
var obj2 = {};
var obj3= {};
wm.set(obj1, "jQuery");
wm.set(obj2, "AngularJS");
wm.set(obj3,"Bootstrap");
document.writeln(wm.get(obj1)+"<br>");
document.writeln(wm.get(obj2)+"<br>");
document.writeln(wm.get(obj3));
</script>
Output:
jQuery
AngularJS
Bootstrap
Example 2
Let’s examine an illustration of how to incorporate elements into a WeakMap object using a chainable format.
<script>
var wm = new WeakMap();
var obj1 = {};
var obj2 = {};
var obj3= {};
wm.set(obj1, "jQuery").set(obj2, "AngularJS").set(obj3,"Bootstrap");
document.writeln(wm.get(obj1)+"<br>");
document.writeln(wm.get(obj2)+"<br>");
document.writeln(wm.get(obj3));
</script>
Output:
jQuery
AngularJS
Bootstrap
Example 3
In this illustration, we will analyze the outcome when varying values are incorporated into the same object.
<script>
var wm = new WeakMap();
var obj1 = {};
var obj2 = {};
wm.set(obj1, "jQuery");
wm.set(obj2, "AngularJS");
wm.set(obj2,"Bootstrap");
document.writeln(wm.get(obj1)+"<br>");
document.writeln(wm.get(obj2)+"<br>");
document.writeln(wm.get(obj2));
</script>
Output:
jQuery
Bootstrap
Bootstrap