#11 Review (while / do / for)


#1

Hi!!

This below code worked for me only once I added the last part which is: while (myCondition);
myCondition = false

I am not sure why the last bit needs to be there since 'do' should run the code either way? Is my logic incorrect here? Would appreciate any help in clarifying why this works. Thanks!!!

// Write your code below!
for (var i = 0; i < 10; i++); {
console.log(i);
}

var myCondition = true;
while(myCondition) {
console.log("I am using a while loop here");
myCondition = false;
}

do {
console.log("I will be printed only be printed once even if the condition is false");
} while (myCondition);
myCondition = false


#2

Well normally you wouldn't want a while loop to run only once, this example they made you do could be a little confusing in that respect.

most of the time you want to make sure your loop runs at-least once; however, if possible it should keep running while the condition is true.

now they set the condition to false at the end, this is so your while loop doesn't go into an infinite loop(since myCondition would always be true without it)

This is a better while loop of that type

myCondition = true;
i = 0;
do {
    console.log("I will be printed only be printed once even if the condition is false");
    if(i < 2){
        i++
    }
    else{
        myCondition = false
    }
} while(myCondition === true)

This will make sure to print to console once, but also keep printing until i is greater than 2.
I hope that makes sense, I can see why you weren't understanding.

Hope that helps :sunny:


#3

Thanks a lot for your help, Edwin!


#4

Your code has 2 issues first the do/while loop where the change of the condition comes after the loop leading to an infinite loop

do {
    console.log("I will be printed only be printed once even if the condition is false");
} while (myCondition);
myCondition = false

and the other one being the semicolon after the for loop:

for (var i = 0; i < 10; i++); {

This should only print 10 once instead of the expected 0-9 being printed. Read this for an explanation what happens:


(It's about conditions but the block idea applies to loops as well)

And maybe have a look at this post for examples for the loop types: