The following code snippet outputs 10,10,10,10,10,10,10,10,10,10
var fs = []
for (var i = 0; i < 10; i++) {
fs.push(function() {return i;})
}
console.log(fs.map(function(f) {return f()}).join())
Whereas if var
in for loop is changed to let
as below, the output is 0,1,2,3,4,5,6,7,8,9
Can someone please help understand this scoping issue and the mysterious way in which JS works?