What are the actual uses of ES6 WeakMap?

Technology CommunityCategory: JavaScriptWhat are the actual uses of ES6 WeakMap?
VietMX Staff asked 3 years ago

WeakMaps provide a way to extend objects from the outside without interfering with garbage collection. Whenever you want to extend an object but can’t because it is sealed – or from an external source – a WeakMap can be applied.

WeakMap is only available for ES6 and above. A WeakMap is a collection of key and value pairs where the key must be an object.

var map = new WeakMap();
var pavloHero = {
    first: "Pavlo",
    last: "Hero"
};
var gabrielFranco = {
    first: "Gabriel",
    last: "Franco"
};
map.set(pavloHero, "This is Hero");
map.set(gabrielFranco, "This is Franco");
console.log(map.get(pavloHero)); //This is Hero

The interesting aspect of the WeakMaps is the fact that it holds a weak reference to the key inside the map. A weak reference means that if the object is destroyed, the garbage collector will remove the entire entry from the WeakMap, thus freeing up memory.