It's a scope issue. By the time the last function is called, i
is where it was last seen at that scope last which would be 10. You can prevent this with a closure.
function multipliers(max){
var a = [];
for(var i=0; i<max; i++){
(function(i){
a.push(function(x){return x*i});
})(i);
}
return a;
}
In this case, the closure is a self-executing function that scopes off i
at each step of the loop. If this did not happen the scope would go to the multipliers
function itself. Since the loop has already completed by the time you are calling the function which you pass 5
to, which happens to be at step 2
of the Array that multipliers
returns, i
has already reached 10
. Obviously, 10*5 is 50. When the closure is used i
s last position is 2
within the scope it is in, giving you the result that is sought. 5*2 = 10.
console.log(multipliers(10)[2](5));