A closure in JavaScript is a feature where an inner function remembers and can access variables from its outer (parent) function, even after the outer function has finished executing.
🔹 What is a Closure?
In simple words:
A closure is formed when a function “closes over” its lexical scope.
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
✔ inner() still remembers count
✔ Even though outer() has already executed
This is closure.
🧠 Why Closures Exist (How They Work)
- JavaScript uses lexical scoping
- Functions remember where they were created, not where they are called
- The inner function keeps a reference to outer variables (not a copy)
🎯 Why Do We Use Closures?
1️⃣ Data Privacy (Encapsulation)
Closures help create private variables.
function createUser() {
let password = "secret";
return {
checkPassword(pwd) {
return pwd === password;
}
};
}
const user = createUser();
user.checkPassword("secret"); // true
✔ password cannot be accessed directly
✔ Used heavily in secure logic
2️⃣ Maintaining State Between Calls
function counter() {
let count = 0;
return () => ++count;
}
const inc = counter();
inc(); // 1
inc(); // 2
✔ State is preserved
✔ Used in counters, caches, trackers
3️⃣ Function Factories
Functions that generate customized functions.
function multiplyBy(x) {
return function (y) {
return x * y;
};
}
const double = multiplyBy(2);
double(5); // 10
4️⃣ Callbacks & Async Code
Closures are everywhere in async JavaScript.
function fetchData(url) {
return function () {
console.log("Fetching from:", url);
};
}
setTimeout(fetchData("/api/users"), 1000);
✔ Callback remembers url
5️⃣ Module Pattern (Before ES Modules)
const module = (function () {
let data = [];
return {
add(item) {
data.push(item);
},
get() {
return data;
}
};
})();
✔ Encapsulated logic
✔ No global pollution
⚠️ Common Pitfall (Interview Favorite)
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 1000);
}
Output:
4 4 4
Why?
varis function-scoped- All callbacks close over the same
i
✔ Fix with let (block scope)
❌ Downsides of Closures (Important)
- Can cause memory leaks if overused
- Retained variables stay in memory
- Harder debugging if abused
🎯 Short Interview Answer
A closure is a function that remembers variables from its outer scope even after the outer function has executed.
Closures are used for data privacy, maintaining state, function factories, callbacks, and implementing module patterns in JavaScript.
⭐ One-line summary
Closures let functions remember and use variables from their creation scope, enabling private state and powerful abstractions.