WeakMap and WeakSet
WeakMap and WeakSet in JavaScript
WeakMap and WeakSet are data structures that hold weak references to objects. They are designed for situations where you want to store data without preventing the Garbage Collector from freeing those objects when no other references exist.
WeakMap is similar to Map, but with the following limitations:
const wm = new WeakMap();
let user = { name: "Ani" };
wm.set(user, "some metadata");
console.log(wm.get(user)); // "some metadata"
user = null; // Now there are no references to the object => GC can remove it and it will be cleared from WeakMap too
When to use WeakMap:
WeakSet is similar to Set, but:
const ws = new WeakSet();
let user = { name: "Karen" };
ws.add(user);
console.log(ws.has(user)); // true
user = null; // Now the object can be cleaned by GC
When to use WeakSet:
Property | Map / Set | WeakMap / WeakSet |
---|---|---|
Can contain primitive values | Yes | No, objects only |
Implement iterable interface | Yes | No |
Can retrieve all contents | Yes | No |
Compatible with GC | No - holds strong references | Yes - weak references, GC can clean |
WeakMap and WeakSet are designed for situations where we want to store data associated with objects without preventing their collection by the garbage collector. They are powerful tools for avoiding memory leaks and ensuring efficient memory management.