π JavaScript Closures β Ace This Common Interview Question
A closure is a feature in JavaScript where an inner function has access to the variables of an outer function even after the outer function has returned.
π A closure has access to:
Its own scope (variables defined between its
{}
).The scope of the outer function.
The global scope.
π¦ Syntax Example
function outer() {
let counter = 0; // local variable
return function inner() {
counter++;
console.log(counter);
};
}
const increment = outer();
increment(); // 1
increment(); // 2
increment(); // 3
Even though outer()
has finished executing, the counter
variable is preserved in memory because the inner()
function closes over it.
β
Common Use Cases for Closures (ES6+)
π 1. Data Privacy / Encapsulation
function createCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.getCount()); // 1
No one can directly modify
count
βclosure keeps it private.
π§ͺ 2. Function Factories
function makeMultiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = makeMultiplier(2);
console.log(double(5)); // 10
β‘ 3. Memoization
function memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) return cache.get(n);
const result = fn(n);
cache.set(n, result);
return result;
};
}
const factorial = memoize(function f(n) {
return n <= 1 ? 1 : n * f(n - 1);
});
π§ 4. Closures with Event Listeners
function setupButton(id) {
let clickCount = 0;
document.getElementById(id).addEventListener('click', function () {
clickCount++;
console.log(`Clicked ${clickCount} times`);
});
}
π‘ 5. Functional Patterns (Currying)
const add = a => b => a + b;
const add5 = add(5);
console.log(add5(10)); // 15
π§΅ Summary
Closures = Functions + Their Lexical Environment.
They preserve state across calls and time.
Very powerful for modular, functional, and secure JS design.