What is a Closure?
- A closure is created when an inner function remembers and can access variables from its outer function even after the outer function has finished executing.
Example:
function outer() {
let name = "Raksha";
function inner() {
console.log(name);
}
return inner;
}
const myFunction = outer();
myFunction();
Output:
Raksha
Here,
- outer() is called.
- name is created inside outer().
- inner() is created and uses name.
- outer() finishes execution.
- Normally, you might think name is gone.
- But inner() remembers name.
- When we call myFunction(), it can still access "Raksha".
That is a closure.
Why do we use closures?
Closures are useful for:
- Data privacy
- Counters
- Callbacks
- Event handlers
- Maintaining state
- Function factories
- Async JavaScript
- Real-life example
Think of a bank account:
function bankAccount() {
let balance = 1000;
return {
deposit: function(amount) {
balance += amount;
},
getBalance: function() {
return balance;
}
};
}
const account = bankAccount();
account.deposit(500);
console.log(account.getBalance());
Output:
1500
The balance variable cannot be directly accessed from outside:
console.log(account.balance);
It gives:
undefined
But the inner functions can access it because they close over balance.
Top comments (0)