Let’s get some closure
So far so good. Let’s take a look at a new example to understand closures. This will look very similar to the examples we’ve seen before with very minimal changes.
1const scopeCheck = () => {
2 let b = 20;
3 const innerScopeCheck = () => {
4 let a = 10;
5 let ret = a + b;
6 b++;
7 return ret;
8 }
9 return innerScopeCheck;
10}
11let fun1 = scopeCheck();
12let fun2 = scopeCheck();
13
14console.log("Function 1 first execution: " + fun1());
15console.log("Function 1 second execution: " + fun1());
16console.log("Function 1 third execution: " + fun1());
17
18console.log("Function 2 first execution: " + fun2());
The output of the following code snippet will be as shown below.
1Function 1 first execution: 30
2Function 1 second execution: 31
3Function 1 third execution: 32
4Function 2 first execution: 30
Let’s quickly run through each run of the function’s execution. In the first run, variable b is created inside the scopeCheck() method, it is added with the variable 10 which is created inside the innerScopeCheck() method. They are both added and assigned to the ret
variable. After this, we increment b
by 1 and then return ret. In the last line of the scopeCheck() method, we return the innerScopeCheck() method.
We have two variables fun1
and fun2
each with the return values from the scopeCheck() method. Ideally, when we execute fun1 three times, the output should be 30 right? Why is the incremented value of b getting added to the subsequent executions? That is the work of a closure.