How Closures Capture State
Understand the lexical environment of closures.
What Is a Closure
A closure is a function bundled together with references to the variables from the scope where it was defined. The inner function "remembers" those variables even after the outer function has returned.
function outer() {
const message = "hello";
function inner() {
console.log(message); // sees outer variable
}
inner();
}
outer(); // "hello"Returning the Inner Function
The magic appears when you return the inner function. It keeps access to the outer variable even though outer has already finished running.
function outer() {
const message = "remembered";
return function () {
console.log(message);
};
}
const fn = outer();
fn(); // "remembered"All lessons in this course
- How Closures Capture State
- Private Variables with Closures
- The Module Pattern (IIFE)
- Factory Functions