I'm trying to figure out why these anonymous functions are returning the last value of my loop iterator as opposed to the iterator's current value when it is set. I thought that values are exempt from pass by reference, but it looks like these return values are pointers to the original i?
function myFunctions(n) {
var list = [];
for (var i = 0; i < n; i++) {
list.push(function(){
return i;
});
}
return list;
}
var res = [];
myFunctions(4).map(function(el){
res.push(el());
});
var p = document.createElement('p');
p.innerHTML = res.join(',');
document.body.appendChild(p);
//expected result: 0,1,2,3
Reading material: Javascript by reference vs. by value
Fiddle: http://jsfiddle.net/ZP2hM/