🔒 Closures = Scope + Privacy
Variables leak globally? Closures create private scope. Data privacy, factory functions, state management.
📝 Closure Examples
// Basic closure
function outer() {
let privateVar = 'secret';
return function inner() {
console.log(privateVar); // 'secret'
};
}
const closure = outer();
closure(); // Uses privateVar
// Private counter
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getValue: function() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
console.log(counter.getValue()); // 2
// Factory functions
function createUser(name) {
let _name = name;
let _age = 0;
return {
getName: function() {
return _name;
},
setName: function(newName) {
_name = newName;
},
getAge: function() {
return _age;
},
setAge: function(newAge) {
if (newAge > 0) {
_age = newAge;
}
}
};
}
const user = createUser('Alice');
console.log(user.getName()); // 'Alice'
🎯 Advanced Closure Patterns
// Memoization
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key] === undefined) {
cache[key] = fn(...args);
}
return cache[key];
};
}
const expensiveFn = (n) => n * n;
const memoized = memoize(expensiveFn);
console.log(memoized(5)); // Computed
console.log(memoized(5)); // From cache
// Module pattern
const Calculator = (function() {
// Private members
let result = 0;
function validate(value) {
return typeof value === 'number';
}
return {
// Public methods
add: function(value) {
if (validate(value)) {
result += value;
}
return this;
},
subtract: function(value) {
if (validate(value)) {
result -= value;
}
return this;
},
getResult: function() {
return result;
},
reset: function() {
result = 0;
return this;
}
};
})();
Calculator.add(5).subtract(2).add(10);
console.log(Calculator.getResult()); // 13
// Partial application
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
const triple = multiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
💡 Closure Use Cases
- Private variables (data privacy)
- Factory functions
- State management
- Memoization (caching)
- Event handlers with state
“Closures enable privacy and state. Private variables, factory functions. Essential for JavaScript mastery.”
