JavaScript WeakMap() Constructor
The WeakMap() Constructor produces WeakMap objects that are a key/value pair array in which the key is referenced weakly. The keys should be objects and the values could be arbitrary. The difference between Map and WeakMap is that keys must be objects and are only weakly referenced. This means that if there are no other strong references to the key, the garbage collector can remove the element in WeakMap.
Syntax:
new WeakMap( iterable )
Parameters: It accepts an optional parameter that can be any iterable object. An iterable is an array-like object with key-value pairs in the elements. The created WeakMap will include each key-value pair. The null is considered undefined.
Below examples illustrates the WeakmMap Constructor:
Example: The get() method is used to retrieve a value associated with the key. If no value is associated with the key, it returns undefined.
Javascript
<script> const o1 = {}, o2 = {}; const wp = new WeakMap([[o2, 17]]); console.log(wp.get(o2)); console.log(wp.get(o1)); </script> |
Output:
17 undefined
Example: The set() method is used to assign a value to the key. It returns the WeakMap object, which allows you to chain.set() calls.
Javascript
<script> const o1 = {}, o2 = {}; const wp = new WeakMap(); wp.set(o1, 100).set(o2, 200); console.log(wp.get(o1)); console.log(wp.get(o2)); </script> |
Output:
100 200
Example: The has() method is used to determine whether an element with a given key exits in a WeakMap. It returns true if it exits otherwise, it returns false.
Javascript
<script> const o1 = {}, o2 = {}; const wp = new WeakMap([[o2, 17]]); console.log(wp.has(o2)); console.log(wp.has(o1)); </script> |
Output:
true false
Example: The delete() method is used to delete an element with a specific key. It returns true if the element existed and was removed otherwise, it returns false.
Javascript
<script> const o1 = {}, o2 = {}; const wp = new WeakMap([[o1, 77]]); console.log(wp. delete (o2)); console.log(wp. delete (o1)); </script> |
Output:
false true