You are unlikely to be asked this question directly, because technical interviews usually focus on classic structures like Map/Set. But if you also mention WeakMap, WeakSet, and WeakRef, it will almost certainly earn you a few extra points. At the very least, you will be remembered, and you will quite likely hear something like: “Nice that you brought up these things too”. So let's figure out what they are.
WeakMap
WeakMap is a ключ → значення map, similar to a regular Map, but with an important difference:
- only objects can be used as keys
- these keys are held as weak references
What is a "weak reference" and why do we need it? - With a regular Map, it is easy to end up in a situation where an object is no longer needed but still "lives" in memory, because a reference to it is held as a key. The GC (Garbage Collector) may reason: "there is still a reference to this object, so it can't be removed".
With WeakMap this doesn't happen: if there are no more strong references to the key object anywhere else, the GC can collect the object, and its entry in the WeakMap disappears automatically. This means a lower chance of memory leaks. This structure cannot be iterated, so there is no for...of, .keys(), .entries(), and not even .size. The API is minimal: set / get / has / delete.
Typical use case: storing "private" data/metadata for objects (cache, state, counters) without creating a memory leak.
WeakSet
WeakSet is like Set (unique values), but it holds only objects, and they are also held as weak references. Just like the previous structure, Set cannot be iterated.
Typical use case: marking objects (for example, as "already processed") without preventing the GC from collecting them.
WeakRef
WeakRef is a wrapper that holds a weak reference to an object (also called target or referent). The idea is this: you kind of "hold a handle" to the object, but there is no guarantee that it will always exist. The GC can collect it at any moment.
What it's for: very careful caching/optimizations, when you want to "peek" at an object without forcibly keeping it in memory. Also, it is important that WeakRef must not be relied upon as stable data storage — deref() can return undefined at any moment.