Search code examples
javascriptfunctionclosureslexical-closures

How does the Javascript closure with function works?


Hi i have been exploring closures and javascript core concepts i couldn't understand why does the console.log(factory[i]) outputs undefined i have pushed my function inside there right? And if i call temp outside the loop it says undefined whereas if i call inside the loop it returns am bit confused can anyone explain me?Here is my code

var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
   var temp=function()
   {
      console.log(fruits[i]);
   }
  factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
   temp(i);
   console.log(factory[i]);
}

https://jsfiddle.net/kh3okLca/


Solution

    1. You are not passing function but the result of the executed function temp() as it don't return anything its undefined. change factory.push(temp()); to factory.push(temp);

    2. The temp() outside return undefined because by that time loop has executed and the value of i is 2 check this following piece of code which logs value of i.

    var fruits=["apple","orange"];
    var factory=[];
    for(var i=0;i<fruits.length;i++)
    {
    	var temp=function()
      {
      	console.log(fruits[i],"console",i);
      }
      factory.push(temp);
    }
    temp();
    console.log(factory,"factory");
    for(var i=0;i<factory.length;i++)
    {
     	temp(i); //i resets to 0 here in same scope
        console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed
    }