mohan babu
mohan babu

Reputation: 1448

Understanding JavaScript Closures with a small example

I am trying to get around understanding javascript closures from a practical scenario.I know from a theoretical perspective , With the help of closures inner functions can have access to the variables in the enclosing function i.e parent function.

I have read a couple of questions on stackOverflow as well.

i am really missing the point of what is happening here?

var foo = [];
for(var i=0;i<10;i++){
  foo[i] = function(){
  return i;
}  
}
console.log(foo[0]());

This gives me out a 10. Most of the articles say that by the time it reaches the inner anonymous function, The for loop is getting executed as a result the last value that is present in the loop which is 10 is being printed.

But i am still not able to get to the bottom of this.

On Contrary, If i use something like:

var foo = [];
for(var i=0;i<10;i++){
 (function(){
   var y =i;
   foo[i] = function(){
   return y;
 }
 })();
 }
console.log(foo[0]());

I am getting the output.Any help would be highly appreciated.

Upvotes: 0

Views: 49

Answers (2)

NonPolynomial
NonPolynomial

Reputation: 329

maybe this code block helps

var foo = [];
for(var i = 0; i < 10; i++) {
    foo[i] = function() {
        return i; // is a reference and will always be the value, which 'i' have on function execution
    }
}
// 'i' is 10 here!
console.log(foo[0]()); // executing the function will return the current value of 'i'

///////////////////////////////////////

var foo = [];
for(var i=0;i<10;i++) {
    /* thats a IIFE (immediately invoked function expression) */
    (function(a) { // 'a' is now a local variable
        foo[a] = function() { // defines a function
            return a; // is a reference to local variable 'a'
        };
    })(i); // <- passing the current value of i as parameter to the invoked function
}
// 'i' is 10 here
console.log(foo[0]()); // returns the reference to 'a' within the same scope, where the function was defined

Upvotes: 2

hackerrdave
hackerrdave

Reputation: 6706

In your first scenario, all of your functions added to the foo array are referencing the same var i. All functions will return whatever i was set to last, which is 10 because during the last iteration of the loop that's what it's value was set to.

In the second scenario, you are Immediately Invoking this function:

(function(){
  var y =i;
  foo[i] = function(){
    return y;
  }
})();

By immediately invoking it you are effectively locking in the local state of var y, for each iteration of the loop - it provides a unique scope for each function added to the array.

Upvotes: 2

Related Questions