When to 'while' and when to 'for'? Javascript


#1

I was trying the When to 'while' and when to 'for' loop topic in Javascript and typed the following for and while loops in the codeacademy interface. The strange thing in the output was it contained an extra line which I didnt called for.
Code:
for (var i=0; i<5; i++){
console.log (i+". x");
}
i=0;
while (i<=5){
console.log (i+". x");
i++;
}
And the output is like this:
0. x
1. x
2. x
3. x
4. x
0. x
1. x
2. x
3. x
4. x
5. x
5

Why the last line contain a 5? (However if I execute the while loop at the beginning before the for loop then it looks ok.)


#2

the codecademy console has the habit of echoing the last variable, as you can see here (you might need to press run in the upper right corner), it works like expected


#3

It is not just the codecademy console but this seems to be a general feature of many consoles, in fact if you would directly use:

while(i<=5){console.log(i+". x");i++;}

in the jsBin console tab you'd get the same additional output as well. It just seems to be a quick response to the user input. Once found the explanation that javaScript buffers one value at a time and that the last value that is in the buffer is displayed once the program is terminated. Unfortunately idk if this is true but it would explain it a bit.


#4

i do get 5x on jsbin:

5. x

but codecademy produces:

5. x
5

#5

sure if you press run but if you enter the console tab in jsBin and write:

var i=0; //enter
while(i<=5){console.log(i+". x");i++;} //enter

you'll see the same additional 5.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.