Closures
A closure gives you access to an outer function’s scope from an inner function. This is a mystery feature of JavaScript functions that most developers fail to understand. It is not a feature that can be created manually .
Now let's write some code to understand much clearly,
const add = function() {
let sum = 0;
return function() {
sum++;
console.log(`${sum}`);
}
}
Now let's store the output in a variable called total()
.
const total = add();
Before starting to run, Our code will be in the global execution context
, and in there we will have total
variable. When the total
function is called it is placed on the top of add
function.
Now remember each execution context have variable environment which contains all local variables and in this case it contains only the sum
The scope looks something like this,
The local scope gets access to all the parent scope
in this case the global scope
So the global context also contains the new total
variable and when the function returns the execution context just pops off from the stack and disappears. So the total
function done his job and really gone now.
Till now we haven't met the closure all we did is understand behind the scenes of total
function.
Now let's call the function total()
,
total(); // 1
total(); // 2
total(); // 3
So this means the total
function in fact able to increment itself to 1 ,2, 3
, But how come total
function have access to add
function at the top 🤔 .
The total function is simply a global scope, the environment is no longer active but it somehow has access to sum
variable and that's exactly what closure does.
We can say closure remember all the variables that existed in the birthplace and Any function will have access to the variable environment in which the function was created.
In this case, the total
function was created in the execution context of add
. So therefore the total
will have access to to variable environment and this is how the function will be able to read and manipulate the variable. So this small connection is called as Closure
Conclusion
Closures are one of those subtle concepts in JavaScript that are difficult to grasp at first. But once you understand them, you realize that things could not have been any other way.
Hopefully, these step-by-step explanations helped you really understand the concept of closures in JavaScript!
Thanks for reading my blog & Let's connect! 🙌🏼
Follow me for more similar articles :D
Feel free to subscribe to my Youtube Channel & Follow me on Twitter <3