Array of functions in javascript: cannot understand the results

I cannot 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 in the result for both, as if the value i for each function in the array was 5. Could you help me understand this?

+3


source to share





All Articles