The closure has three scope chains listed as follows:
Let's understand the closure by using an example.
In the above program we have two functions: fun() and innerfun(). The function fun() creates the local variable a and the function innerfun(). The inner function innerfun() is only present in the body of fun(). The inner function can access the outer function's variable, so the function innerfun() can access the variable 'a', which is declared and defined in fun().
This is the closure in action in which the inner function can have access to the global variables and outer function variables.
The entire body of function innerfun() is returned and stored in the variable output, due to the statement return innerfun. The inner function is not executed only by using the return statement; it is executed only when followed by the braces ().
In the output, the code will display the value of the variable 'a', defined in the parent function.
Now, there is another example in which we will use the parameterized function
In the above program there are two parameterized functions: fun() and innerfun(). The function fun() has a parameter a, and the function innerfun() has the parameter b. The function fun() returns a function innerfun() which takes an argument and returns the multiplication of a and b. In the program, the output is the closure.
Now, there is another example of closure within a loop.
0 1 2 3 4
Closure points the variable and stores the reference of a variable. They don't remember the variable's value. In the above code, we are updating the function closure() argument with every call. So, we will get the different values of the variable i, at different index.