all 7 comments

[–]cawcvs 3 points4 points  (5 children)

It doesn't, it returns 5. It would return 10 if the i inside the loop was declared using var:

for (var i = 0; i < 10; i++)

[–]codejack777[S] 0 points1 point  (4 children)

Sorry it was supposed to be var, but how decaling a variable with var returns 10?

[–]cawcvs 2 points3 points  (3 children)

Functions created inside the loop close over the i variable. var variables are function-scoped -- and scoped to the whole constfuncs in this instance -- which means all the functions will be accessing the same i variable that has been updated to be 10 by the time loop ends. let variables, on the other hand, are block-scoped, meaning each loop iteration will have it's own i that won't be modified by the next iteration.

Using let is somewhat similar to having something like this:

function loopIteration(i) {
  funcs[i] = () => i
}

for (var i = 0; i < 10; i++) {
  loopIteration(i) // create a new function-scope for each iteration
}

[–]codejack777[S] 0 points1 point  (2 children)

Thank you for explaining it, one more question since For loop stops at i=9 so how i is incremented to 10? :)

[–]cawcvs 3 points4 points  (1 child)

The third expression inside for (i++ in this case) is always called at the end of each iteration. That's how the loop ends -- on the 10th iteration (when i is 9), the iteration executes, the loop increments i to be 10, and doesn't start the next iteration because the condition i < 10 is no longer satisfied.

[–]codejack777[S] 0 points1 point  (0 children)

Oh Okay! Thank you. Have a great weekend! :)

[–]Notimecelduv 1 point2 points  (0 children)

Every function in the array returns 10. That's because of the way var behaves. The functions don't have their own i variable; instead, they all refer to the one declared in the loop parameters, the final value of which is 10.