The attached code returns 3, 3 & 3. If I change var to let, it returns 1, 2 & 3.
Why is this?
I expected both to return 1, 2 & 3. I understand that Var is function scoped, and let is block scoped - but how does that play out here?
function buildFunctions () {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
function () {
console.log(i);
}
);
}
return arr;
}
let fs = buildFunctions();
fs[0]();
fs[1]();
fs[2]();