Closures are often introduced as an “advanced concept,” but the idea is surprisingly simple.
A closure happens when a function retains access to variables from its outer scope even after the outer function has executed.
Think of it like this
You create a private variable inside a function.
Then you return another function that can still access that variable.
Even though the outer function is done,
the inner function keeps the variable alive.
Example
function outer() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Here, count is preserved between function calls.
That’s a closure.
Why Closures Matter
Data privacy
Maintaining state
Functional programming patterns
Closures are not magic.
They’re just JavaScript remembering scope.
Top comments (0)