🔒 Quick Win: Closures are functions that remember their outer variables. They’re the foundation of functional programming in JavaScript.
Closures are powerful but often misunderstood. Master them for better code.
🚀 What are Closures?
// ✅ Basic closure
function createCounter() {
let count = 0; // Outer variable
return function() {
count++; // Inner function remembers count
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// ✅ Closure with parameters
function createMultiplier(multiplier) {
return function(x) {
return x * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
💡 Real-World: Private Variables
// ✅ Create private variables with closure
function createUser(name, email) {
let _password = null; // Private variable
return {
getName() { return name; },
getEmail() { return email; },
setPassword(password) {
_password = password;
},
validatePassword(password) {
return password === _password;
}
};
}
const user = createUser("John", "john@email.com");
console.log(user.getName()); // "John"
console.log(user._password); // undefined (private!)
user.setPassword("secret");
console.log(user.validatePassword("secret")); // true
💡 Expert Tip: Closure Performance
// ❌ Too many closures (memory issues)
function createManyClosures() {
const closures = [] ;
for (let i = 0; i < 100000; i++) { closures.push(() => i); // ❌ Each has its own closure
}
return closures;
}
// ✅ Use shared closure
function createSharedClosure()
{
let value = 0;
const closures = [];
for (let i = 0; i < 100000; i++) { closures.push(() => value++); // ✅ Shared closure
}
return closures;
}
// ✅ Closures in React
function useCustomHook()
{
const [state, setState] = useState(initial);
// ✅ Closure for stable callback
const stableCallback = useCallback(() => {
// Closure captures state
return state;
}, [state]);
return stableCallback;
}
