Navigate
Search topics, hooks, and fundamentals
A closure is a function that remembers the variables from where it was created — even after that scope is gone. Like sealing a value in a time capsule.
When a function is created inside another function, it captures (closes over) the variables in its outer scope. Even after the outer function finishes, the inner function still has access to those variables.
Each capsule seals a different value. Click one to create a closure, then open it to see what was captured:
The inner function returned by createGreeting remembers name from when it was created. Each call seals a different value:
function createGreeting(name) {
// 'name' is sealed into the capsule
return function () {
console.log("Hello, " + name + "!");
};
}
const greetAlice = createGreeting("Alice");
const greetBob = createGreeting("Bob");
greetAlice(); // "Hello, Alice!"
greetBob(); // "Hello, Bob!"
// Each function remembers its own 'name'JavaScript looks up variables through a chain of scopes. A closure preserves this chain, giving inner functions access to all outer variables:
When inner() needs a variable, JavaScript walks up the scope chain until it finds it. Click a scope level to highlight it:
Closures let you create truly private variables. The count variable below can only be accessed through the returned functions:
function makeCounter() {
let count = 0; // sealed in the capsule
return {
increment: () => ++count,
getCount: () => count,
};
}
const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2
// 'count' is private — only accessible via closures