0

I understand that var cause a single binding for an i in a loop.

Can somebody explain why the answer is 5? Does i++ increments one more time on a function call?

Try to debug it, but still confused about workings of a loop.

var result = [];

for(var i = 0; i < 5; i++){
  result[i] = function(){
    return i;
  }
}
console.log(result[0]())
Roma Kim
  • 321
  • 1
  • 8
  • *"In the example below, I understand that since loop is in the global scope, variable `i` is saved and remembered due to closures."* Yes, but it's a global and all functions share it, because you've used `var`. Variables declared with `var` are scoped to the containing function (if there were one) or global scope (in your example). That one `i` is closed over by all functions created in the loop, so they all see the value of `i` as it was at the **end** of the loop (`5`). ... – T.J. Crowder Sep 14 '22 at 11:36
  • ... If you used `let` (`for (let i = 0; i < 5; ++i)`), there would be a different `i` for the block for each loop iteration, the functions would each close over their own `i`, and you'd see the output you expect (`0` from `result[0]`, `1` from `result[1]`, etc.). – T.J. Crowder Sep 14 '22 at 11:36

0 Answers0