Review ("for" vs "while" loop outcome)


#1

This code ran in "Review", however, I was actually aiming for the log to be "0 1 2 0 1 2 Looping once!" only to have it resulted in "0 1 2 1 2 3 Looping once!" Somehow my "for" and "while" loops are not matching up correctly. Why is the "while" loop not giving me "0 1 2"? Trying to understand. Thanks!


// This is a "for" loop.
for (var forNum = 0; forNum <= 2; forNum++) {
    console.log(forNum);}
    
// This is a "while" loop.
var whileNum = 0;
    while (whileNum <= 2) {
    whileNum++;
    console.log(whileNum);
    }
    
// This is a "do/while" loop.
var doMessage = false;
do {
    console.log("Looping once!");
} while (doMessage);


#2

here:

while (whileNum <= 2)

you use <=, which mean the loop will also run for whileNum is 2, which is then increased to 3 (whileNum++) and logged to the console


#3

And I though the "for" loop and the "while" loop are the same, with only having to switch the "sentences" around. You are explaining that that is not the case then. /_\
The "for" loop I am telling it that forNum is and also starts with 0, then count by adding 1, and count only up to 2. >>> "0 1 2"
The "while" loop I was telling it that whileNum is 0, but don't count that 0? Is there a way that I can switch anything around to get it to print "0 1 2" WITHOUT doing the following?

var whileNum = -1;
    while (whileNum <= 1) {
    whileNum++;
    console.log(whileNum);
    }

My brain is figuring this out. Thanks again, stetim94! ^^


#4

you can do this for the while loop as well, but then you have to first console.log whileNum and then increase whileNum, then while includes the start number

The problem this creates, is console behaviour, which echoes the value of the updated variable because you update a variable after the last console.log


#5

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