Chapter XXIV · Advanced Concepts
WeakMap
A `WeakMap` is a collection of key-value pairs where keys must be objects and are held *weakly*, allowing automated garbage collection.
01 How It Works
Think of temporary sticky notes attached to items that vanish automatically when the item is discarded.
Unlike standard Maps, WeakMap keys do not prevent garbage collection if the key object has no other active references.
example.js
const wm = new WeakMap();
let obj = {};
wm.set(obj, "metadata value");
// If 'obj' reference is removed, it is garbage collected automatically from WeakMap
1. Initialize a `WeakMap` instance.
2. Set object references as keys (`wm.set(obj, val)`).
3. Allow keys to be garbage collected when unreferenced.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const cache = new WeakMap();
function process(obj) {
if (cache.has(obj)) return cache.get(obj);
let result = "computed";
cache.set(obj, result);
return result;
}
Key Takeaway
WeakMaps prevent memory leaks by holding object keys weakly for garbage collection.