0

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?

  • there are already thousands of explanations out there... – Jonas Wilms Jun 23 '17 at 17:03
  • Read about: **closures** and **scoping**. – ibrahim mahrir Jun 23 '17 at 17:06
  • If you use `var` it will be as if you declare the variable before the `for` loop (thus all iteration share a reference to the same variable and when that variable get incremented, the functions in the array try to access the value of that variable, since they all have a reference to the same one, they print the same value). When using `let`, each iteration creates a new variable, thus each function has a reference to its own version of the variable. – ibrahim mahrir Jun 23 '17 at 17:09

0 Answers0