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
WeakMap is similar to Map, but with the following limitations:
- Keys must be objects only (not strings or numbers)
- It's not iterable, meaning you can't use `for...of` or `forEach`
- You cannot retrieve all of its contents
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:
- When you want to store "private" data for objects without interfering with their garbage collection
- Used in caches and for storing metadata
WeakSet
WeakSet is similar to Set, but:
- Contains only objects (no primitive values)
- Also not iterable
- If the only reference to an object is in WeakSet, GC will remove it
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:
- When you need to remember only which objects you've already processed
- Useful in observer patterns and for creating visited markers
Difference Between Map/Set and WeakMap/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 |
Conclusion
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.