Closure in JavaScript Explained with Counter App Example
What is a Closure?
A closure is a feature in JavaScript.
A closure is created when an inner function remembers and accesses variables from its outer function, even after the outer function has finished execution.
Basic Example
function outer() {
let message = "This is outer function scope";
function inner() {
console.log(message);
}
return inner;
}
let result = outer();
result(); // Output: This is outer function scope
Explanation:
outer()runs and returns theinnerfunction- Normally,
messageshould be destroyed afterouter()finishes - But
inner()still remembersmessage - This behavior is called a closure
Key Concept
Even after the outer function is executed:
- Its variables are still accessible inside the inner function
- That memory is preserved due to closure
Benefits of Closures
1. Data Privacy
Variables inside the outer function are not accessible globally.
console.log(message); // Error
Only the inner function can access them.
2. State Preservation
Closures allow you to maintain state across function calls.
Real Use Case – Counter Example
function counterApp() {
let data = 0;
return {
increment: function () {
console.log(++data);
},
decrement: function () {
console.log(--data);
}
};
}
let counter = counterApp();
HTML Buttons
<button onclick="counter.increment()">Increment</button>
<button onclick="counter.decrement()">Decrement</button>
How it works:
datais private- It cannot be accessed directly
- But it is still remembered and updated through closures
Output Behavior
Clicking buttons:
- Increment → 1, 2, 3...
- Decrement → decreases value
Even though counterApp() has already executed, data is still preserved.
Why Closures Are Important
Closures are widely used in:
- Event handlers
- Callbacks
- Data hiding
- Functional programming
- Real-world applications like counters, timers, and modules