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.
Top comments (2)
This is not correct. A closure is created every time ANY function is created - at the time of that function's creation. Also, nesting functions is not required for the creation of a closure.
Misconceptions About Closures
Thanks for the clarification! Youโre right that technically a closure is created whenever a function is created, since the function carries its lexical environment with it.
In this article, I simplified the explanation using nested functions because the blog is aimed at beginners and students who are just starting with JavaScript. Nested functions are often the easiest way to demonstrate how closures allow access to variables from an outer scope.
I appreciate you pointing out the more precise definition!