JavaScript DO WHILE loop example.

This is a beginner’s tutorial on how to create a DO/WHILE loop in JavaScript. In plain English, a DO WHILE statement will DO something WHILE a certain condition is TRUE. i.e. The code block inside the DO statement will execute as long as the condition in the WHILE brackets equates to true. However, there is one caveat.

Let’s take a look at a basic example:

//Setup a counter variable
var counter = 1;

do{
    //Do this piece of code.
    console.log('Current number is: ' + counter);
    counter++;
}
//While the following condition is TRUE.
while(counter <= 10);

The DO/WHILE statement above is pretty simple. It will log to the browser console as long as the counter variable is less than or equal to 10.

Essentially, our code is saying this:

  • DO: Log to to the console and increment the counter variable.
  • WHILE: The counter variable is less than or equal to 10.

Once the counter variable reaches 11, the condition will no longer equate to TRUE. This is because 11 is obviously not less than or equal to 10. It is greater than 10. As a result, the condition in the WHILE block will equate to FALSE and code inside the DO block will no longer be executed. This ends the loop in question.

A DO WHILE statement will always execute at least once.

One of the most important things to note about DO/WHILE statements is that the DO block will always execute at least once. This is because the DO block comes before the WHILE condition check. Thus, it will be executed before the condition can be checked.

Take a look at the following example:

//Set the counter to 11.
var counter = 11;

do{
    //Do this piece of code.
    console.log('Current number is: ' + counter);
    counter++;
}
//While the following condition is TRUE.
while(counter <= 10);

If you run the JavaScript snippet above and check your browser’s developer console, you will see that the DO block is executed. This is despite the fact that the counter variable has been set to 11.

If you do not want this to happen, then you will need to use a for loop or a while loop instead.

Hopefully, you found this guide useful!