JavaScript Closures
14 April 2025 | Category: JavaScript
In JavaScript, a closure is created when a function “remembers” variables from its outer scope, even after that outer function has finished executing.
Closures are a fundamental concept that gives functions access to the variables that were in scope when they were created.
✅ Definition
A closure is a function that closes over its lexical environment—which means it can access variables defined outside its scope, even after the outer function is done running.
🔁 Basic Example
function outer() {
let name = "Devin";
function inner() {
console.log("Hello " + name);
}
return inner;
}
const greet = outer(); // 'outer' runs and returns 'inner'
greet(); // Output: Hello Devin
Even though
outer()
has finished running, theinner()
function still remembers thename
variable. This is a closure in action.
🧠 Why Are Closures Useful?
Closures allow:
- Data encapsulation (like private variables)
- Function factories (functions that return functions)
- Callbacks with state
- Maintaining state in asynchronous code (like
setTimeout
or event listeners)
🔐 Private Variables Example
function counter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const increment = counter();
increment(); // 1
increment(); // 2
increment(); // 3
count
is “private” to thecounter()
function and preserved between calls using the closure.
⏱ setTimeout Closure Example
function greetLater() {
let name = "Dev";
setTimeout(function () {
console.log("Hello " + name);
}, 2000);
}
greetLater(); // Output after 2 seconds: Hello Dev
Even after greetLater()
finishes, the function inside setTimeout()
remembers the name
variable—because of the closure.
🧩 Common Mistake Without Closure
for (var i = 1; i <= 3; i++) {
setTimeout(function () {
console.log(i); // Always logs 4, 4, 4
}, i * 1000);
}
✅ Fixed using Closure:
for (var i = 1; i <= 3; i++) {
(function (j) {
setTimeout(function () {
console.log(j); // Logs 1, 2, 3
}, j * 1000);
})(i);
}
📌 Summary
- Closures happen when an inner function keeps access to its outer function’s variables, even after the outer function has completed.
- They are useful for data hiding, asynchronous code, and function factories.
- Understanding closures helps you write cleaner, more efficient JavaScript.