do while loops
In some cases, you really need the code block to be executed at least once. For example, if you need valid user input, you need to ask at least once. The same goes for trying to connect with a database or some other external source: you will have to do so at least once in order for it to be successful. And you will probably need to do so as long as you did not get the result you needed. In these cases, you can use a do while loop.
Here is what the syntax looks like:
do {
// code to be executed if the condition is true
} while (condition);
It executes what is within the do
block, and then after that it evaluates the while
. If the condition is true
, it will execute what is in the do
block again. It will continue to do so until the condition in the while
changes 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...