9. the do/while loop


#1
var loopCondition = false;

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

What is "while (loopCondition)" doing and what does it mean? I take it out but it returns an error. "do" says to print out something and I don't see what's stopping it from doing so. loopCondition is already set as false so nothing should be interfering with it working without "while (loopCondition)"


#2

The do while loop is a while loop in reverse. Where the structure of a normal while loop is

while keyword (condition) {body}

the structure of a do while loop is

do keyword {body} while keyword (condition);

still the idea is the same: while condition is true -> execute {body}
The only major difference, apart from this awkward way of writing it, is that in the first run the {body} comes before the condition. So no matter what value the condition is, even if it is false, the body is still executed at least once. And that is the whole purpose of a do while loop to avoid writing more than you need.

var password;
...
password = prompt(...);
while(password != "12345"){
   password = prompt(...);
}

as you can see this line is written twice: password = prompt(...); once before the loop always and then inside the loop based on the condition. With a do while loop doing the same thing it would be just:

do{
       password = prompt(...);
}while(password != "12345");

PS: Probably the do keyword is just to distinguish it from a regular while loop as

{...}
while(condition);

would probably be interpreted as:
regular code with unnecessary {} around it + while(condition);
And unfortunately while(condition); is a very dangerous but valid while loop as you might understand when knowing about this:


#3

Oh, ok I think I see. Is it always a "do/while" or can you have code that just says "do"? I tried removing the "while" part but the "do" part doesn't run so I'm assuming there's no "do" command?


#4

Afaik the do is only meant to be used in a do while loop (Tried an explanation for it's occurrence under PS:). What kind of problem do you have where it might be useful to have a do without a while and how do you expect it to behave? :slightly_smiling:


#5

Oh alright. I just wanted to understand the code better.