What a Closure Actually Is
You'll learn: The precise definition of a closure and why it's one of JavaScript's most powerful features.
The Core Idea
A closure is a function that retains access to variables from its outer (enclosing) scope, even after that outer scope has finished executing and "exited."
Think of it like a backpack: when a function is created inside another function, it packs up references to any variables it needs from the outer function and carries them along wherever it goes—even after the outer function has returned.
How It Works
When you define a function inside another function, the inner function "closes over" the outer function's variables. This happens automatically thanks to lexical scope—the inner function remembers where it was created, not where it's called.
function makeCounter() {
let count = 0; // This variable belongs to makeCounter's scope
return function increment() {
count++; // Inner function accesses outer variable
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Even though makeCounter has finished executing, the increment function still has access to count. The inner function "closed over" that variable—that's the closure.
Why It Matters
Without closures, count would disappear when makeCounter returned. Closures let us create functions with private, persistent state.
Key Takeaway: A closure is created when an inner function captures variables from its outer scope, preserving access to those variables even after the outer function completes.