Let's learn what closures are and how they work!
1. What Is a Closure?
A closure happens when a function remembers variables from the scope where it was created, even after the outer function has finished executing.
In simple words, a function can remember the variables around it.
2. Understanding Closures with an Example
function outer() {
let message = "Hello";
function inner() {
console.log(message);
}
inner();
}
outer();
Output:
Hello
Here, the inner() function can access the message variable because it is inside the outer() function.
But what happens if we return the inner function instead?
3. A Real Closure Example
function outer() {
let message = "Hello";
function inner() {
console.log(message);
}
return inner;
}
const myFunction = outer();
myFunction();
Output:
Hello
Let's understand what happens:
-
outer()creates themessagevariable. - The inner function is returned and stored in
myFunction. - The
outer()function finishes executing. - We call
myFunction(). - The inner function still remembers the
messagevariable.
This is a closure!
The inner function remembers the variables from its surrounding scope, even after the outer function has finished executing.
4. Closures Can Remember Changing Values
Let's look at another example.
function counter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const myCounter = counter();
myCounter();
myCounter();
myCounter();
Output:
1
2
3
Why does this happen?
- Initially,
countis0. - Each time we call
myCounter(),countincreases by1. - The function remembers the same
countvariable between calls.
This is one of the most common examples of closures in JavaScript.
5. Why Are Closures Useful?
Closures are useful for:
- Remembering data between function calls.
- Creating counters.
- Keeping variables private.
- Maintaining state without using global variables.
For example, the count variable in our counter example cannot be accessed directly from outside the function.
console.log(myCounter.count);
Output:
undefined
The variable is not a property of myCounter. It remains in the surrounding lexical environment that the closure can access.
Conclusion
Closures are easier to understand when you remember one important idea:
A function can remember variables from the scope where it was created, even after that scope's outer function has finished executing.
Keep practising closures with small examples like counters and private variables. They will help you understand more advanced JavaScript concepts and React.
Happy Coding! 🚀
Top comments (0)