Closure in JavaScript

Most of the JavaScript Developers use closure consciously or unconsciously. Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide a better control over the code when using them. And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers.

Let’s see and understand closure through an example.
Example 1:

// Explaination of closure
/* 1 */function foo()
/* 2 */{
/* 3 */var b = 1;
/* 4 */function inner(){
/* 5 */returnb;
/* 6 */}
/* 7 */returnn;
/* 8 */}
/* 9 */var get_func_inner = foo();        
/* 10 */console.log(get_func_n());
/* 11 */console.log(get_func_n());
/* 12 */console.log(get_func_n());

Explanation:Interesting thing to note here is from line number 9 to line number 12 . At line number 9 we are done with the execution of function foo() but we can access the variable which is defined in function foo() through function inner() i.e in line number 10, 11, 12. and as desired it logs the value of b. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables.
Output of the above code:
Output_example_1

In order to see the variable and function bound within closure we can write as:

/* 13 */console.dir(get_func_inner);

Output:
Output_dir_for_function
As we can see the variables within the closure in the scope section.

Definition of Closure:

In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b]
-Wikipedia

or

In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed

Now lets look at the another example.
Example 2:

function foo(outer_arg) {
    function inner(inner_arg) {
        returnouter_arg + inner_arg;
    }
    returninner;
}
var get_func_inner = foo(5);
console.log(get_func_inner(4));
console.log(get_func_inner(3));

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 execution of inner function produce the summation of outer_arg and inner_arg as desired.
Output:
Ouput_example2

Now let’s see an example of closure within a loop.
In this example we would to store a anonymous function at every index of an array.
Example 3:

// Outer function
function outer()
{
    var arr = [];
    var i;
    for(i = 0; i < 4; i++)
    {
        // storing anonymus function
        arr[i] = function () { returni; }
    }
    // returning the array.
    returnarr;
}
var get_arr = outer();
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());

Output:
Output_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.
Lets see an correct way to write the above code so as to get different values of i at different index.
Example 4:

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

Ouput:
Output_example3_modified
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.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/closure-in-javascript/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar