Open In App

JavaScript WeakMap

JavaScript WeakMap is used to store a collection of key-value pairs that are weakly referenced which means if garbage collection is possible it would not be prevented. In a WeakMap the keys are strictly objects but values can be any primitive JavaScript Data Type. A WeakMap is not enumerable as the references are loose. WeakMaps are mainly used to store extra data where cleaning of memory does not affect the program much 

Syntax:



new WeakMap()
new WeakMap(iter)

Parameter: It has only one optional parameter.

Example 1: In this example, we will construct a weakmap object and element, then check whether the element exists.






function myGeeks() {
    let looseMap = new WeakMap();
    let Ram = {name};
    let Raj = {name};
    let Rahul = {name};
    looseMap.set(Ram, "Ram");
    looseMap.set(Raj, "Raj");
    looseMap.set(Rahul, "Rahul");
    console.log(looseMap);
    console.log(looseMap.has(Ram))
}
myGeeks();

Output:

WeakMap {{…} => 'Raj', {…} => 'Rahul', {…} => 'Ram'}
true

Example 2: In this example, we will understand how garbage collection works in WeakMap.




let looseMap = new WeakMap();
let Ram = {name};
looseMap.set(Ram, "Ram");
console.log(looseMap);
Ram = null;
console.log(looseMap)
setTimeout(function(){
    console.log(looseMap);
}, 300)

Output: As the reference is removed from the memory so the value in looseMap are garbage collected

WeakMap {{…} => 'Ram'}
WeakMap {{…} => 'Ram'}
WeakMap {}

Supported Browsers:

We have a complete list of Javascript WeakMap methods, to check those please go through this JavaScript WeakMap Complete Reference article.


Article Tags :