Back to course

The 'do...while' Loop Structure

JavaScript: The Complete '0 to Hero' Beginner Course

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 TypeWhen to Use
forWhen the number of iterations is known (e.g., looping through an array).
whileWhen the number of iterations is unknown, and the loop might not need to run at all.
do...whileWhen the loop body must execute at least once.