Open In App
Related Articles

JavaScript WeakMap

Improve Article
Improve
Save Article
Save
Like Article
Like

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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials