Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Closure in Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 293
    Comment on it

    A closure is a technique which helps us to access the variable of other function even when they are out side the scope of the calling function. We can also say that it has access to the outer functions private variables.


    Example : The private variable of any function can be accessed out side of the function with the help of Closure technique.


    Scenario where you might use it
    i) Access to its own scope
    ii) Access to the outer functions variables and
    iii) Access to the global variables


    Closures can be particularly useful when dealing with callbacks.


    Example:

    function
    makeList(list) {
    var result = [];
    for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push(function () { alert(item + ' ' + list[i]) });
    }
    return result;
    }
    function showList() {
    var list = makeList([1, 2, 3]);
    for (var j = 0; j < list.length; j++) {
    list[j]();
    }
    }
    
    1. makeList() function will be called 3 times by showList() function as there are 3 array elements in makeList() function parameter.
    2. Array variable result[] will be populated with self invoked functions and will be return to it's calling function showList()
    3. Self invoking function will be executed just once only.
    4. Now the returned value by makeList() function will be assigned to Variable list.
    5. Lastly, the loop will be executed 3 times and it will show the output in form of alert message showing item of list.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: