I am currently having trouble understanding the following Javascript code and after searching a bit I still cannot figure it out. I've included the function below
function buildFunctions(){
var arr = [];
for(var i = 0; i < 3; i++){
arr.push(function(){
console.log(i);
})
}
return arr;
}
var fs = buildFunctions();
fs[0]();
fs[1]();
fs[2]();
Question: Can someone please help me understand why the following code produces all 3's instead of 0, 1, 2?
I'd really like to understand exactly what's going on here, but I don't see why the functions doesn't output 0, 1, 2