For = ok, while = ok, do / while =?


#1

// Write your code below!
//for loop
for(i = 0; i <= 5; i++){

console.log( i + " for");
}

//while loop

var i = 0;
while(i <= 5){

console.log(i + " while");
i++;
}

//do / while loop
do {

var i = 0;
console.log(i + " do");

}
while(i < 5){

    console.log(i + " do");
    i++;
    }

Hi! Need some help.
This is my code for the Review of loops course.
The for and the while loops are fine, i guess, although if i comment out the do/while loop (which is the problem i need help with) in the while loop at the end i get this extra 5 :
0 for
1 for
2 for
3 for
4 for
5 for
0 while
1 while
2 while
3 while
4 while
5 while
5

which i don't want to..I don't understand the origin of the extra 5 .
And then there is the do/while loop.If i submit the code my page crashes.
I shouldn't declare the i variable in the do ?
Thank you very much for your help!


#2

@ibigspot,
Please read

The Instructions:
To finish up and prove your loop mastery,
write three syntactically correct loops in the editor:
one for,
one while, and one do. while
Beware of infinite loops!

the for-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

the while-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

the do-while-loop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while

At end then place one extra code-line
console.log( "End-of-code" );


#3

Ok the 5 is harmless. The console has this feature that it echoes the last value that occurs in your code so if you have a blank page and enter 2+2 you'd get 4 on the screen. So what you see is the value of this: i++;
So this is not a problem and if it really bothers you maybe place a console.log as the last statement of your code as it has no value of its own (undefined).

About the do/while loop. Well that is not how this works. The idea is that in a usual while loop you have your condition and if it is true you run the code in {}. A do while loop is a little different. Here you run the code in {} (after do) once before anything else (even if the condition is false) then you come to the condition and if it is true you go back to do and repeat the loop. So the loop body is really that {} between do and your while with the condition. What you added in {} after while has nothing to do with this and will only be interpreted after the loop which is as said this:

do {

   var i = 0;
    console.log(i + " do");

}
while(i < 5){

is done. As you probably found out by now the code that let's this stop is inside the {} after the loop but as this is unreachable you end up in an infinite loop.


#4

Thank you very much guys.
Now it's pretty obvious. :slightly_smiling: