0

Can anyone explain what is happening here?

for (var i = 0; i < 10; i++) {
  /* ... */
}
console.log(i);

//expect 9 as loop states i < 10, however it shows 10

I would expect when i is logged that it would show a value of 9. From what I understand is that the loop will run from 0-9 and then will stop as the loop states that i < 10. However, when I console.log(i) it shows 10. Can anyone explain why this is the case?

1
  • 3
    Try re-writing this as a while loop and you'll see what is happening Commented Dec 2, 2015 at 17:24

4 Answers 4

5

The increment happens before the last check.

In other words, the loop ends if and only if i >= 10, so it follows that after the loop ends, i must be at least 10.

The loop happens like this:

  1. Set var i = 0;

  2. Check if i < 10 (true), execute loop.

  3. Execute i++.

  4. Repeat step 2 and 3 until i < 10 is false (in this case, until i = 10).

Sign up to request clarification or add additional context in comments.

1 Comment

Lovely, perfect explanation
1

What you have,

for (var i = 0; i < 10; i++) {
    /* ... */
}
console.log(i); // logs 10

Can be re-written as a while

var i = 0;
while (i < 10) {
    /* ... */
    i++;
}
console.log(i); // logs 10

And now we see that at the end of i === 9 there is one last increment made so i === 10, causing the condition to fail thus exiting the loop.

1 Comment

also, a good explanation. Thanks Paul. Fairly basic stuff, but never noticed it so explicitly before. Good to understand it perfectly now
0

Because the loop exits when it is not less than 10. i.e. when i == 10

The order of operation of the following for loop:

for(a;b;c) {
    d;
}

Is this:

A, repeat(b, d, c) while b==true

Where the last statement called is b. This means that the statement just before b is c

2 Comments

Your "is this" looks like a do..while and not a while. Just write it as a regular while
Correct. But I was trying to write it in more English-type semantics, rather than code. I had originally written "A, B, D, C, B, D, C, B" but that didn't really get the idea across the way I wanted either.
0

That loops runs until i = 10, then stops. You are then console logging the 10.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.