39. The do...while Loop
The do...while loop is very similar to the while loop, but with one crucial difference: the condition is checked after the code block executes.
This guarantees that the loop body will always run at least once.
Syntax
javascript do { // Code to execute (Always runs at least once) } while (condition);
Example: Guaranteed Execution
We use a prompt to ask the user for a non-empty name. The loop guarantees the prompt appears at least once, and repeats if the condition (userName is empty) is true.
javascript let userName;
do { userName = prompt('Enter your name (cannot be empty):'); } while (userName === '' || userName === null);
console.log('Welcome, ' + userName);
| Loop Type | When to Use |
|---|---|
for | When the number of iterations is known (e.g., looping through an array). |
while | When the number of iterations is unknown, and the loop might not need to run at all. |
do...while | When the loop body must execute at least once. |