Closures and Garbage Collection
What You'll Learn
You'll understand how closures keep variables alive in memory and what that means for your program's resource usage.
How Closures Affect Memory
In JavaScript, the garbage collector automatically frees up memory when variables are no longer needed. Normally, when a function finishes executing, its local variables are cleaned up. But closures change this behavior.
When a closure captures variables from its outer scope, those variables cannot be garbage collected—even after the outer function has returned. Why? Because the closure still references them. The JavaScript engine keeps them alive as long as the closure itself exists.
function createCounter() {
let count = 0; // This variable is captured by the closure
return function increment() {
count++;
console.log(count);
};
}
const counter = createCounter();
// createCounter() has returned, but 'count' is NOT garbage collected
// because the closure (increment function) still references it
counter(); // 1
counter(); // 2
// 'count' stays in memory as long as 'counter' exists
The Memory Implication
Think of it like a book on loan: as long as someone has checked it out (the closure exists), the library (JavaScript engine) can't remove it from circulation (garbage collect it). Only when you return the book (the closure is no longer referenced) can the library reclaim that shelf space.
let counter = createCounter();
counter(); // 'count' is in memory
counter = null; // Now the closure is unreferenced
// JavaScript can now garbage collect both the closure AND 'count'
Key Takeaway: Closures extend the lifetime of captured variables—they remain in memory until the closure itself is no longer referenced and can be garbage collected.