Question

Why does this:

i=0;
while(i<=4){
    console.log(i);
    i = i+1;
} 

outputs: 0,1,2,3,4,5 but it should stop on the 5-th( 0,1,2,3,4 ) element not 6th(5)

PS: this happens if you paste the above code in google chrome console

Was it helpful?

Solution

The 5 isn't in logged in the loop, but its the i variable.

i=0;
while(i<=4){
    console.log("log: " + i);
    i = i+1;
} 

OTHER TIPS

This is the normal behavior under Chrome. It displays the last line evaluated. For instance, if you just enter: i=5; it will display 5 even though you didn't ask to display it through console.log. In your example the last line evaluated is i=i+1; which, at this point, computes the 5 value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top