What is the key difference between how a `Map` and a `WeakMap` handle their keys, and what is the primary consequence of this difference?
React JS interview question for Advanced practice.
Answer
Map keys are held strongly, WeakMap keys weakly; this allows WeakMap entries to be garbage collected.
Explanation
A Map holds strong references to its keys, which prevents them from being garbage collected as long as the map exists. A WeakMap holds weak references, which does not prevent them from being garbage collected. The primary consequence is that WeakMap entries are automatically removed when their key object is garbage collected, thus preventing memory leaks.