đ§ Introduction
Closures are one of the most powerfulâyet confusingâfeatures in JavaScript. If you've ever wondered how JavaScript "remembers" variables after a function has run, this post is for you.
By the end, youâll understand what closures are, why they matter, and how to use them like a pro.
đ What Is a Closure?
A closure is a function that remembers the variables from its lexical scope, even after that outer function has finished executing.
In simple terms:
A closure lets a function access variables defined outside its scopeâeven after the outer function is done running.
đŚ Basic Example
function outer() {
let count = 0;
return function inner() {
count++;
console.log(`Count is: ${count}`);
};
}
const counter = outer();
counter(); // Count is: 1
counter(); // Count is: 2
counter(); // Count is: 3
â
Even though outer()
has finished running, inner()
still has access to count
. Thatâs closure in action.
đ§° Real-Life Use Cases
1. Data Privacy (Encapsulation)
function createSecret() {
let secret = 'đľď¸ââď¸';
return {
getSecret: () => secret,
setSecret: val => secret = val
};
}
const obj = createSecret();
console.log(obj.getSecret()); // đľď¸ââď¸
obj.setSecret('đ');
console.log(obj.getSecret()); // đ
đ Variables like secret
stay hidden from the outside world.
2. Function Factories
function multiplier(factor) {
return function (x) {
return x * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10
đ double
is a closure that remembers factor = 2
.
â Common Pitfall
Closures inside loops can be tricky:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 3, 3, 3
â
Fix with let
:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 0, 1, 2
đ§ Final Thoughts
Closures are everywhere in JavaScriptâfrom callbacks and event handlers to React hooks and private state.
Mastering them will deepen your understanding of how JavaScript really works.
đŹ Whatâs Next?
- Want to dive into currying, memoization, or scope chains?
- Let me know in the comments or drop a â¤ď¸ if you found this useful!
Top comments (0)