Mark As Completed Discussion

Let's get some Closure Continued 2
We can see a new scope when we take a look at the console.log() statement. There is a new scope called Closure. Since we haven’t executed the fun1 yet, the value of b is 20. Let’s execute fun1 once and see what the value of the Closure is. Change the code as shown below.

JAVASCRIPT
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.dir(fun1);

Following the same process as we did before, let’s inspect the output on the console. This is where the concept of closures become crystal clear. If we went by the conventional way of executing a method, we would’ve thought variable b would be created each time the method is executed. But with the closure scope, each time the innerScopeCheck() method is executed, it checks for the value of b in closure scope and finds the updated value there, and uses it. That is why we see an increment in the value with each execution of the fun1() method.

Let's get some Closure Continued 2

We hope you have understood the concept of closures in JavaScript. They are sometimes tricky to get a hang of. But as soon as you understand it completely, you will wonder how can it be done any other way.