A closure in JavaScript means:
A function remembers the variables from the place where it was created, even after that outer function has finished running.
Think of it like a function carrying a backpack 🎒 of variables from its parent scope.
1. Simple Real-World Example (Bank Account)
Imagine a bank account where only a few functions can access the balance.
function createAccount(initialBalance) {
let balance = initialBalance;
return function deposit(amount) {
balance += amount;
console.log("Balance:", balance);
};
}
const myAccount = createAccount(1000);
myAccount(500);
myAccount(200);
//Output:
//Balance: 1500
//Balance: 1700
What happens?
createAccount(1000) runs.
- It creates a variable balance = 1000.
- It returns the deposit function.
- Normally balance should disappear after createAccount finishes.
- But because of closure, the deposit function remembers balance
👉 The function keeps access to balance even after the outer function finished.
That is Closure.
2. Another Real Example (Private Counter)
Suppose you want a counter that nobody can change directly.
function createCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const counter = createCounter();
counter();
counter();
counter();
//Output:
//1
//2
//3
Here:
- count is private
- Only the returned function can access it
- The function remembers count
Again → Closure
3. Very Simple Analogy
Think of a chef writing a recipe 🍲
- The chef writes the recipe in the kitchen.
- Later someone cooks it in another place.
- But the recipe still remembers the ingredients from the kitchen. Similarly:
Function + Remembered Variables = Closure
4. Why Closures Are Useful
Closures are commonly used for:
- Data privacy (private variables)
- Counters
- Event handlers
- Callbacks
- Functional programming Example in real apps:
- Login sessions
- API caching
- React hooks
- Module pattern
5. One-Line Definition (Interview Style)
A closure is created when a function remembers and accesses variables from its outer scope even after the outer function has finished executing.
One more easy example:
function outer() {
let name = "Rahul";
return function inner() {
console.log(name);
};
}
const fn = outer();
fn();
What happens?
- outer() runs.
- Variable name is created.
- inner() is returned.
- Normally name should disappear ❌
- But inner() remembers it ✅
Output:
Rahul
👉 Because inner function remembers name → Closure.
Top comments (0)