How do WeakMap and WeakSet differ from Map and Set, and how do they help prevent memory leaks?
Understanding garbage collection, weak references, and common leak sources.
JavaScript reclaims memory via garbage collection: an object is collected once nothing reachable references it. A Map/Set holds STRONG references to its keys/values, so anything stored there stays alive as long as the collection does — a classic leak when you use it as a side cache keyed by objects (DOM nodes, component instances) and forget to delete entries. WeakMap (object keys only) and WeakSet hold WEAK references: if the key object becomes otherwise unreachable, the entry is garbage-collected automatically. That makes them the right tool for associating private/auxiliary data with an object whose lifetime you don't control — per-node metadata, memoization keyed by object identity, marking 'seen' objects — without pinning those objects in memory. The trade-off: because entries can vanish at any time, WeakMap/WeakSet are not enumerable and have no size or iteration. Common leak sources to name in an interview: forgotten timers/intervals, detached DOM nodes still referenced in JS, event listeners never removed, and closures capturing large scopes. WeakRef and FinalizationRegistry give even lower-level control but are rarely needed and should be a last resort.
Caching or attaching metadata keyed by object identity, tracking objects you don't own, and any per-object side table that must not prevent GC.
O(1) get/set/has; entries auto-released when keys are unreachable.