A closure is a powerful and fundamental concept in JavaScript that allows a function to “remember” the variables from its outer (enclosing) scope even after that scope has finished executing.
Understanding Scope First
In JavaScript, each function creates its own scope. Variables defined inside a function are not accessible from outside that function.
function outer() {
let message = "Hello";
function inner() {
console.log(message); // Accesses variable from outer scope
}
inner();
}
outer(); // Output: Hello
Closures in Action
Now let’s see what happens when we return the inner function instead of calling it directly:
function outer() {
let message = "Hello";
return function inner() {
console.log(message);
};
}
const greet = outer(); // outer() returns inner()
greet(); // Output: Hello
Even though outer() has finished executing, the inner() function still has access to message. That’s a closure!
Why Are Closures Useful?
- Data privacy (like private variables)
- Maintaining state between function calls
- Creating factory functions or function factories
Real Example: Private Counter
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Here, the variable count is kept “private” inside the closure. It’s not accessible from outside but still maintained across function calls.
Closures and Loops
Closures are often used with loops to preserve variable values:
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i); // Outputs 3, 3, 3
}, 1000);
}
This happens because i is shared. You can fix it with a closure using let or an IIFE:
// Using let
for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i); // Outputs 0, 1, 2
}, 1000);
}
Conclusion
Closures allow inner functions to access variables from an outer function even after that outer function has returned. They are essential for writing clean, modular, and powerful JavaScript code—especially when you need data privacy or want to keep state.
Post a Comment