Ketan Jadhav
Closures in JavaScript
According to the internet, javascript is an object-oriented programming language commonly used to create interactive effects within web browsers.
Many of us use javascript in our day to day life, but we never paid attention to concepts of it. JavaScript closures are one of those concepts that many people have trouble understanding.
If you want to save yourself from the so-called monsters of JavaScript, you must understand how it works. I’ll explain what a closure is in clear terms and relate it to a real-life example to make it easier to remember.
So, What is Closure?
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables.
Let’s understand it using below code snippet:
Here we have two functions:
- An outerFunc with variable f_name and returning innerFunc.
- An innerFunc with its variable l_name and also accessing outerFunc variable f_name.
The scope of variable f_name is limited to the outerFunc function, and the scope of a variable l_name is limited to the innerFunc function.
Now, what happened when this line of code was executed.
var getName = outerFunc();
getName();
Result of outerFunc() gets stored in a variable called getName and now is a function type.
And, Now comes the interesting part.
When getName() function gets executed:
- It creates a variable called l_name and assigns a value John to it.
- Now, javascript try to execute console.log(“Name: “, f_name, l_name); , javascript knows that l_name variable is exist as it is just now created, but f_name is no longer existed because f_name is a part of outerFunc() and it will only exist if outerFunc() is in execution. So here f_name is no longer exists.
Then how will we get the f_name variable?
The answer is Closure!, yes you heard it right.
During the execution of the parent function, it passes its scope chain to the child function, and in this way, the child can access the variables that are preserved(closure) in the preserved variable.
So, our innerFunc() will preserve the variable f_name=”John” when the outerFunc() is implemented and kept holding it.
Now, on execution of getName function(child function), it has its own scope now, and scope also contains variable f_name because it has preserved variable within its own closure(scope) at the execution of parent function.
In this way, Javascript knows f_name = “John” and l_name = “Washington” , and we will get output as: Name: John Washington.
Closure stores the references of variables of outer function.
Hurrey!Now you have completely understood what closure is in javascript.
Conclusion:
Closures are one of those concepts in javascript which is difficult to understand at the beginning, But one if you understand it carefully, it isn’t that bad or difficult.
Closures will allow us to access the variables and functions even after the execution of those functions has done.