Your functions all contain a reference to the same variable sq
, which has the value 25
once you actually call the functions. You need to create a separate closure for each function, each with its own copy of sq
's value, in order to capture the value of sq
at the time you want:
function sqFnList(a){
var b = [];
for ( var i = 0; i <a.length; i++)
{
var sq = a[i] * a[i];
b[i] = function (the_sq) {
return function() { return the_sq;}
}(sq);
}
return b;
}
x = sqFnList([3,4,5])[0]() // x is 9
Here's a fiddle to demonstrate.