do while loop

The code within the do while loop will be performed at least once even if the comparison used returns false the first time then the comparison is used each time afterward to determine whether or not it should repeat.


var MyVariable = 1;
do {
     document.write("This is a do while loop in action.");
     MyVariable++;
}
while (MyVariable < 10);

The do while loop code looks similar to the while loop code. It starts with the declaration of the variable then the do keyword follows. The do keyword makes sure that the code block is executed at least once.

In our case the document.write() is executed once then is executed 8 more times until the variable value reaches the value of 10 (by increasing with 1 each time).

Below is an example of do while loop that is executed just once because the comparison returns false.


var MyVariable = 15;
do {
     document.write("This is a do while loop in action.");
     MyVariable++;
}
while (MyVariable < 10);

Only the value of he variable MyVariable is changed. Now the value is 15 which is not less than 10.

Leave a Reply