JavaScript WeakMap and WeakSet: Associating Data Without Leaks
Weak collections let you attach data to objects without keeping them alive. Here is when and how I use them. WeakMap and WeakSet are the collections I reach for when I need to associate extra data with objects I do not own, without preventing those objects from being garbage collected. They are niche, but in the right situations they solve problems that no other structure handles cleanly. Understanding their constraints is what unlocks using them correctly. What Weak Means A WeakMap holds key-value pairs where must be an object, and the reference to that key is weak. If nothing else references object, the garbage collector may reclaim it, and the corresponding entry disappears from the WeakMap. There is no callback when this happens; the entry simply becomes unreachable. This is the core property: you can annotate objects with metadata that lives exactly as long as the objects themselves. A WeakSet is the weak analogue of a Set: it holds objects weakly and only tells you membership. You cannot iterate a WeakSet or ask for its size, because the contents can change unpredictably as the collector runs. The same non-iterability applies…