2

Looking at this code, if I console log i after the loop terminates, i = 10 but I don't understand how.

i is set to 0 and then increments by one as long as i < 10, so it stops incrementing at 9. So in the log within the loop, i counts from 0 - 9, but when I log i AFTER the loop terminates. It has become 10.

I don't understand how it goes from 9 - 10.

"use strict";

var foo = [];

for (var i = 0; i < 10; i++) {
    console.log(i);
    foo[i] = function() { return  i};
}
console.log(i);

Could anyone explain this to me? Thank you :)

Le Moi
  • 975
  • 2
  • 15
  • 41
  • Although I'm sure they're going to run into that problem later, this question *is not* a duplicate of the question about using loop variables in closures. – Mike Cluck Mar 29 '16 at 20:47
  • Wasn't actually a dupe of that question. However, it's answered simply by the fact that i++ increments your value of i. Once it is outside the valid range (i.e. 10, no longer < 10), then the loop exits. You then display the value of 10, after the loop has completed. – ManoDestra Mar 29 '16 at 20:49
  • @MikeC, you are right. – Nina Scholz Mar 29 '16 at 20:51

5 Answers5

2

After i = 9, the loop increments it to 10. Then it checks if i < 10 which is false and hence your code exits the loop with the value i = 10.

Typically a loop executes in the order

  1. Initialize loop variables
  2. Check if condition is true.
  3. Update the loop variablew
Banach Tarski
  • 1,821
  • 17
  • 36
2

You've got the order mixed up. Here's how it goes:

  1. If i < 10
  2. Execute loop body
  3. Update i (i++)
  4. Return to 1

So the way your loop ends is that i++ moves the value up to 10 then checks the condition. Since i is no longer less than 10, the loop ends.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • @LeMoi Glad I could help :) Heads up! Since you're using `i` inside of those functions you're making, you're going to run into a very common problem. [Check out this question for an explanation of how to deal with it.](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example?lq=1) Good luck! – Mike Cluck Mar 29 '16 at 20:55
1

You have a console.log on your last line. i gets assigned 10 (by adding 1) and then the loop evaluates to see if it should continue, but i has to surpass 9 to stop the loop.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
0

After the last time through the loop, i++ runs one last time, so i is 10. Then the i < 10 condition fails, so the loop exits.

elixenide
  • 44,308
  • 16
  • 74
  • 100
0

loop exits after it reaches 10 see the condition i < 10

sry for the typo

Milan
  • 829
  • 8
  • 12