Chapter X · Closures
Closures
A closure is a function that retains access to its lexical outer scope even after that outer function has finished executing.
01 How It Works
Think of a backpack carrying private items stored securely inside it wherever it travels.
When an inner function captures outer variables, those variables persist in memory via closure references.
example.js
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
1. Define a variable inside an outer function.
2. Return an inner function referencing that variable.
3. Invoke the inner function later to access retained state.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
function makeGreeting(msg) {
return name => `${msg}, ${name}!`;
}
const sayHi = makeGreeting("Hello");
console.log(sayHi("Alice")); // "Hello, Alice!"
Key Takeaway
Closures enable data privacy and persistent state encapsulation.