What is a common memory leak pattern with closures in JavaScript?
Pushing closures into an array or map, where each closure captures a large object. As the collection grows, each entry keeps its large object alive, and the memory grows unbounded. Remove entries when they are no longer needed.
Explore This Question
Search for additional explanations using these tools:
More FAQs in Garbage Collection and Block Scope in JavaScript
When a block ends, its lexical environment is eligible for GC (unless a closure keeps it alive). This lets the GC free block-scoped variables sooner than function-scoped var variables, which stay alive until the function returns.
Because var is function-scoped, not block-scoped. A var inside a block leaks to the enclosing function scope and stays alive until the function returns, even if the block has ended. let and const are freed when the block ends.
Yes. A closure keeps a reference to its lexical environment. As long as the closure exists, the closed-over variables cannot be garbage collected. This is a common source of memory leaks.
Still have questions?
Browse all our FAQs or reach out to our support team
