Chapter X · Closures
How Closures Remember Variables
Closures preserve variable references because inner functions maintain active links to their outer lexical environment records.
01 How It Works
Think of a root anchor system keeping nutrients connected even after the main plant stem is gone.
Even after outer execution context pops off the call stack, the environment record stays alive in heap memory if referenced by a closure.
example.js
function outer() {
let val = "persisted data";
return function inner() {
return val;
};
}
const getVal = outer();
console.log(getVal()); // "persisted data"
1. Outer function creates variables in lexical scope.
2. Inner function references those variables.
3. Engine retains environment data in memory.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
function secretHolder(secret) {
return {
getSecret: () => secret
};
}
Key Takeaway
Closures keep outer scope variables alive in memory as long as inner function references persist.