Open In App

JavaScript WeakMap

Last Updated : 22 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • iter: It is an iterable JavaScript object that implements the @@iterator method. It contains two elements where the first is key and the second is value.

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

Javascript




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.

Javascript




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:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads