What is WeakMap and how does it help with closures and GC in JavaScript?
WeakMap keys are weakly held. When a key is garbage collected, the entry is automatically removed. This prevents memory leaks in caches where closures might otherwise keep keys alive forever.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Closures and the Garbage Collector in JavaScript
Closures hold a reference to their lexical environment, keeping all closed-over variables reachable. As long as the closure is reachable, the GC cannot free those variables. This is useful for data privacy but can cause memory growth.
Extract only what you need (close over len, not the whole array), null references when done (use let instead of const), use WeakMap for caches (keys are weakly held), and use WeakRef for optional references.
Some modern engines optimize this: if a closure does not reference a variable, the engine may free it even though it is in the same lexical environment. But this is an optimization, not guaranteed across all engines.
Still have questions?
Browse all our FAQs or reach out to our support team
