A closure in JavaScript is created when a function remembers and accesses variables from its outer (lexical) scope, even after that outer function has finished executing.
In simple words:
A closure lets a function “remember” the environment it was created in.
🧩 Example:
function outerFunction() {
let count = 0; // variable in outer scope
function innerFunction() {
count++; // inner function accesses outer variable
console.log("Count:", count);
}
return innerFunction;
}
const counter = outerFunction(); // outerFunction executes once
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
🧠 Explanation:
outerFunctionruns and returnsinnerFunction.- Normally, variables inside
outerFunctionwould be gone after it finishes. - But because
innerFunctionstill referencescount, JavaScript keepscountalive — this preserved scope is called a closure.
⚙️ Why Closures Are Useful:
- ✅ Data privacy / encapsulation:
Hide variables that shouldn’t be accessible directly. - ✅ Stateful functions:
Functions that “remember” data between calls. - ✅ Callbacks and event handlers:
Keep access to variables from the parent scope.
💡 Example: Private Counter (Real-life Use)
function createCounter() {
let value = 0; // private variable
return {
increment: function() { value++; return value; },
decrement: function() { value--; return value; },
getValue: function() { return value; }
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getValue()); // 2
📌 value is not accessible directly, only through the functions — this is closure-based privacy.
✅ In short:
A closure is formed when an inner function retains access to its outer function’s variables, even after the outer function has returned.