Minds
It is Recommended to practice while you learn

Closure

A closure is a feature of JavaScript that allows inner functions to access their outer scope. Closure helps in binding a function to its outer boundary and is created automatically whenever a function is created.

Let’s See And Understand Closure Through Some Example.

Example 1 :

Explanation : We can access the variable b which is defined in function foo() through function inner() as the later preserves the scope chain of the enclosing function at the time of execution of the enclosing function i.e. the inner function knows the value of b through it’s scope chain. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables.

function foo()
{
var b = 1;
function inner(){
return b;
}
return inner;
}
var get_func_inner = foo();

console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());

function foo(outer_arg) {

function inner(inner_arg) {
return outer_arg + inner_arg;
}
return inner;
}
var get_func_inner = foo(5);

console.log(get_func_inner(4));
console.log(get_func_inner(3));

Example 2 :

Explanation : In the above example we used a parameter function rather than a default one. Note even when we are done with the execution of foo(5) we can access the outer_arg variable from the inner function. And on the execution of the inner function produce the summation of outer_arg and inner_arg as desired.


Example 3 :

Explanation : Did you guess the right answer? In the above code we have created four closure which point to the variable i which is local variable to the function outer. Closure don’t remember the value of the variable it only points to the variable or stores the reference of the variable and hence, returns the current value. In the above code when we try to update the value of it gets reflected to all because the closure stores the reference.

// Outer function
function outer()
{
var arr = [];
function i;
for (i = 0; i < 4; i++)
{
// storing anonymous function
arr[i] = function () { return i; }
}

// returning the array.
return arr;
}

var get_arr = outer();

console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());

// Outer function
function outer()
{
function create_Closure(val)
{
return function()
{
return val;
}
}
var arr = [];
var i;
for (i = 0; i < 4; i++)
{
arr[i] = create_Closure(i);
}
return arr;
}
var get_arr = outer();
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());

Example 4 :

Explanation : In the above code we are updating the argument of the function create_Closure with every call. Hence, we get different values of i at different index.