Describe a scenario where using a `WeakSet` would be advantageous over a regular `Set`. Explain the tradeoffs involved.
React JS interview question for Advanced practice.
Answer
A WeakSet is advantageous when you need to 'tag' or track a collection of objects without preventing them from being garbage collected. A great example is tracking which image elements in a document are currently visible on the screen. Scenario: An Intersection Observer API watches for images scrolling into view. When an image becomes visible, you want to add it to a collection to trigger a high-resolution load. When it scrolls out of view, you no longer need to track it. If you use a regular Set: When an image becomes visible, you add it to visibleImagesSet. If the image is later removed from the DOM for any reason (e.g., in a single-page app navigation), the Set will still hold a strong reference to that image element. This prevents the element from being garbage collected, causing a memory leak. Advantage of WeakSet: If you use a WeakSet, visibleImagesWeakSet, it holds a weak reference. When the image is removed from the DOM and all other references are gone, the garbage collector can reclaim its memory. The entry in the WeakSet is removed automatically. This allows you to safely track 'live' objects without manual cleanup. Tradeoffs: The primary tradeoff is loss of functionality. A WeakSet is not iterable, has no .size property, and cannot be cleared with .clear(). You can only add, has, and delete items. This is an acceptable price for automatic memory management in this use case.
Explanation
The main tradeoff for the memory safety of a WeakSet is functionality: you cannot iterate it, get its size, or clear it, because its contents can be changed at any time by the garbage collector.