If a function finishes executing, its memory is wiped out. So how does this code remember the count? function…
If a function finishes executing, its memory is wiped out. So how does this code remember the count? function createCounter() { let count = 0; return function() { count++; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3 "createCounter()" executed and popped off the Call Stack on line 10. Yet every time we invoke "counter()", it accesses and increments "count" as if the parent function is still running. Is this a loop? No. This is one of the most powerful features in JavaScript: A Closure. Here is what happens under the hood: 1. What Actually Is a Closure? A closure is simply a function bundled together with references to its surrounding lexical environment. Whenever an inner function uses a variable from its outer parent and is returned or passed elsewhere, it doesn't leave those variables behind—it packs them into an invisible "backpack". 2. Where Is the Variable Stored? (Stack vs Heap) Under normal circumstances: • Local variables live on the Call Stack. Once a function returns, its frame is destroyed. With a Closure: • The V8 engine detects that the returned inner function still needs "count". • Instead of leaving "count" on the stack to be discarded, the engine allocates it into Heap Memory inside a special Closure object. • Even though the Call Stack frame is gone, the reference in Heap memory stays alive. 3. Why Doesn't the Garbage Collector Delete It? JavaScript's Garbage Collector works via "reachability". As long as the variable "counter" holds a reference to that inner function, the inner function holds a reference to the Heap record. Because the link is active, the engine keeps that memory intact. 4. Proof in the Browser DevTools Run this in your console: console.dir(counter); Expand the dropdown ➔ inspect [[Scopes]] ➔ open "Closure (createCounter)". You will literally see: "count: 3" sitting safely in heap storage. This exact mechanism is how private state, factory functions, and React's useState persist data across independent execution cycles without polluting global scope. Have you ever inspected a function's [[Scopes]] property inside DevTools to debug closure leaks?