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.
The below examples illustrate the WeakmMap Constructor:
Example 1: 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
const o1 = {}, o2 = {}; const wp = new WeakMap([[o2, 17]]); console.log(wp.get(o2)); console.log(wp.get(o1)); |
Output:
17 undefined
Example 2: The set() method assigns a value to the key. It returns the WeakMap object, which allows you to chain.set() calls.
Javascript
const o1 = {}, o2 = {}; const wp = new WeakMap(); wp.set(o1, 100).set(o2, 200); console.log(wp.get(o1)); console.log(wp.get(o2)); |
Output:
100 200
Example 3: 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
const o1 = {}, o2 = {}; const wp = new WeakMap([[o2, 17]]); console.log(wp.has(o2)); console.log(wp.has(o1)); |
Output:
true false
Example 4: 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
const o1 = {}, o2 = {}; const wp = new WeakMap([[o1, 77]]); console.log(wp. delete (o2)); console.log(wp. delete (o1)); |
Output:
false true
We have a complete list of Javascript weakMap methods, to check those please go through this JavaScript WeakMap Complete Reference article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.