Why does var not help garbage collection in blocks in JavaScript?
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.
Verify This Answer
Cross-check this information using these trusted sources:
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.
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.
Remove handlers when no longer needed, do not close over large objects unless necessary, use WeakRef or WeakMap where appropriate, and keep closures short-lived. Avoid accumulating closures that each keep a large object alive.
Still have questions?
Browse all our FAQs or reach out to our support team
