9. Why isn't it an infinite loop?


#1

Okay, so the code for 9. The 'do' / 'while' loop activity works like it's supposed to, but could somebody please explain to me why it isn't an infinite loop?

The code looks like this-

var loopCondition = false;

do {
console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
} while (loopCondition);

-but to me that looks like it should be an infinite loop, because

var loopCondition = false

as stated outside the loop. Inside the do part of the do/while loop, it only says

console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");

but then there is no statement that loopCondition would become true.

So because of the lack of "loopCondition = true", shouldn't the code keep running because there is no condition that changes the loop to true, keeping the while part of the loop from infinitely running?

I know that there must be something that I'm missing or don't fully understand, because the code runs fine, my browser didn't crash, and there is no other thread about this that I see. Can someone please tell me why it isn't not an infinite loop? It's very puzzling to me!


#2

Well it's pretty much the other way around :slightly_smiling:
A while loop runs while it's condition is true. So if the condition is false a while loop would not run infinite but not even once. And here comes the special thing about do/while loops.

Where regular while loops go:

condition == true? -> {} -> condition == true? -> {} -> ...-> condtition == false -> go on

do while loops go like this:

do {} -> condition == true -> do{} condition == true? -> do{} -> ...-> condtition == false -> go on

So the code in {} gets executed always at least once! So even if the condition is false you still get the output at least once, after this one free loop it's just a regular while loop the the speciality that the loop body {} comes before the while keyword and not after it.


#3

Okay, thank you so much! I knew that there was something that I was missing!!! Sorry for the late reply!