🟨 JavaScript Intermediate

What is a WeakMap and WeakSet?

Answer

WeakMap is like a Map but with two key differences: keys must be objects (not primitives), and the references to keys are "weak" — if the key object has no other references, it can be garbage collected, and the WeakMap entry is removed automatically. WeakMaps are not iterable (no .size, no .keys()). API: set(obj, value), get(obj), has(obj), delete(obj). Use case: storing private data associated with objects without preventing GC: const privateData = new WeakMap(); class Foo { constructor() { privateData.set(this, {secret: "value"}); } }. WeakSet is like a Set but holds weak references to objects. Membership test only — no iteration, no size. Use case: tracking which objects have been "visited" without keeping them alive. Both avoid memory leaks when keys/values are no longer needed, making them ideal for caching and metadata storage on DOM nodes or other objects with uncertain lifetimes.