1. What is a Closure?
In simple words:
A Closure is when a function remembers the variables from its outer function even after the outer function has finished executing.
Think of it like a school bag 🎒.
A student goes home.
But the bag still contains books from school.
Even outside school, the books are still accessible.
Similarly:
- A function can remember variables from where it was created.
2. Simple Example
function outerFunction() {
let message = "Hello Students";
function innerFunction() {
console.log(message);
}
return innerFunction;
}
let myFunction = outerFunction();
myFunction();
Output
Hello Students
3. How This Works
Step by step:
outerFunction()runs.- It creates a variable
message.
innerFunction()is created inside it.
outerFunction()returns innerFunction.- Even after
outerFunction()finishes,innerFunction()still remembers message.
This memory is called a Closure.
"That ability of remembering the outer variables is called a Closure."
4. Real-Life Example
Imagine a cookie jar 🍪.
function cookieJar() {
let cookies = 5;
function takeCookie() {
cookies--;
console.log("Cookies left:", cookies);
}
return takeCookie;
}
let eatCookie = cookieJar();
eatCookie();
eatCookie();
eatCookie();
Output
Cookies left: 4
Cookies left: 3
Cookies left: 2
Even though cookieJar() finished running, the function still remembers the cookies variable.
5. Why Closures Are Useful
Closures help us to:
- Remember data
- Protect variables
- Create private variables
- Build powerful JavaScript features
Many libraries like React and Node.js use closures.
6. Key Points to Remember
✔ A closure is created when
- A function is inside another function
- The inner function uses variables from the outer function
✔ The inner function remembers those variables even after the outer function ends.
7. Conclusion
Closures may look confusing at first, but they are just about functions remembering their environment.
Whenever an inner function accesses variables from an outer function, a closure is created.
Understanding closures will make you much stronger in JavaScript, because many advanced concepts depend on them.