I'm having trouble with do / while loops


#1

Hey I've been really stumped by this problem I would really appreciate it if someone could help me by explaining what I'm doing wrong here.

So here is the code for a while loop (I made very basic loops for this because I wanted to keep it as simple as possible)

var num = 5;

while (num < 10){
console.log(num);
num++;
};

this code will run will no problem and will print out the numbers 5 to 9 (I don't have problems with the while loops on their own (as far as i am aware lol), just when it is do/while).
That being said here is the code for my do/while.

var num = 5

do {
console.log(num)
} while (num < 10){
console.log(num);
num++;
};

As you can see it is nearly identical to the one above but this will not work. It keeps making an infinite loop. I'm sure I'm doing something wrong but I can't see what.

please help me? :pray:

also please have a look at this next bit of code.
do {
console.log("test");
} while (false){
console.log("random");
};

It prints out "test" and "random". Again I think i must have misunderstood something because as far as I'm aware it should not do anything in the 'while' if the condition is false.

Many thanks in advance


#2

The problem is that you tried something that I'd like to call do while/while loop which does not exist.

The syntax of a do while loop is like this:

do{
   code
}while(condition);

so it you run into problems when you try to append the crucial parts of your loop in {} after while. Because these parts are only executed after the loop is done. Also have a look at the other posts there for more information about loops and some examples on how they can be used and when a specific kind of loop should be used.