JS Do While Loop

JavaScript do...while Loop

In some cases, you really need a code block to be executed at least once. For example, if you need valid user input, you need to ask the user at least once before checking if the input is valid.

The same goes for trying to connect to a database or an external source: you have to try connecting at least once in order for it to be successful. If it fails, you might need to keep trying as long as you don't get the result you need.

In these cases, you can use a do...while loop.

Syntax of the do...while Loop

Here is what the syntax looks like:

do {
    // code to be executed if the condition is true
} while (condition);

How It Works:

  1. It executes what is within the do block first, regardless of the condition.
  2. After that, it evaluates the condition in the while statement.
  3. If the condition is true, it will execute what is in the do block again.
  4. It will continue to do so until the condition in the while statement evaluates to false.

Example: Validating User Input

We can use the prompt() method to get user input. Let's use a do...while loop to ask the user for a number between 0 and 100.

User Input Example

let number;
do {
    number = prompt("Please enter a number between 0 and 100: ");
} while (!(number >= 0 && number < 100));

console.log("You entered a valid number: " + number);

Code Explanation

Imagine the user interacts with the console like this:

Please enter a number between 0 and 100: > -50
Please enter a number between 0 and 100: > 150
Please enter a number between 0 and 100: > 34

Note on console behavior: Everything behind the > is user input here. The > is part of the code; it is added by the console to make the distinction between the console output (Please enter a number...) and the console input (-50, 150, and 34) clearer.

In this scenario, the program prompts the user three times. Because the first two times the number (-50 and 150) was not between 0 and 100, the condition in the while block evaluated to true (meaning: the input is invalid, keep looping).

With 34, the condition in the while block became false (meaning: the input is valid), and the loop finally ended.


Exercise

?

What is the main difference between a while loop and a do...while loop?