3

I can not understand the result provided by an array of functions in javascript

 var myArray = [];
 for (var i=0;i<5;i++){
     myArray.push(function(a){
        return i+a;
     })           
 }

 alert(myArray[0](2));
 alert(myArray[1](2));

I get 7 as a result for both, as if the value of i for each function in the array was 5. Could you help me to understand this ?

Makoto
  • 765
  • 2
  • 17
  • 45
  • 3
    That is because the functions are being called after `for` loop has been finished. So the time the function is being executed the value of `i` is `5`. – Mritunjay Aug 30 '14 at 16:50

0 Answers0