Oleg alex
Oleg alex

Reputation: 99

Why is iterating once more in console.log javascript?

i understand the loops i guess, but im surprised to see in console.log of firebug iterating once more.I expect 10x to iterate(0-9). Why the 10??

$i = 0;

while ($i < 10) {
    console.log($i);//the last time here should be $i=9, not $i=10
    ++$i;
}

// in console log i have(0...10)

while ($i < 10) {
    console.log($i);
    $i++;
}
// in console.log i have doubled 9(0...9,9) Why 9 doubled???

Thanks for you advice

Upvotes: 1

Views: 517

Answers (2)

Loamhoof
Loamhoof

Reputation: 8293

I think the "10" and "9" you don't want you're seeing is what is returned in the console.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816282

I think what you see is just the result of the last statement, which is $i++ or ++$i. If you directly type this statement in the console, you see a number outputed as well, even if you don't explicitly output it.

For example, if I run the code directly in Firefox's console, I actually see

10
0
1
...
9

The 10 is the result of the last execution of ++$i and the others are the console.log statements, which are only executed after the code terminated (as it seems).

If you use

console.log('Iteration: ' + $i);

then you will see the difference more clearly.


That's also the reason why you see two 9s, since the result of $i++ (where $i = 9) is 9.

Upvotes: 3

Related Questions