do...while LoopIn 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.
do...while LoopHere is what the syntax looks like:
do {
// code to be executed if the condition is true
} while (condition);
do block first, regardless of the condition.while statement.true, it will execute what is in the do block again. while statement evaluates to false.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.
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);
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.
What is the main difference between a while loop and a do...while loop?