Run Once with do...while
Run Once with do...while
A do...while loop executes its body before checking the condition. This is useful for a first attempt that must occur, even when the continuation condition is already false.
Before this topic, review Trace a while Loop if its terms are unfamiliar.
What you’ll learn
- Explain run once with do...while through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The body still runs once, but that execution now adds 2.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
let attempts = 0;
do {
attempts++;
} while (false);
console.log(attempts);
Expected output
1Run in JavaScript compiler →Introduction to do...while Loop in JavaScript
The do...while loop is one of JavaScript's control flow statements that ensures the loop body executes at least once — no matter what. If you've ever needed to run a block of code before checking a condition, this loop is your go-to.
Syntax of do...while
do {
// code to be executed
} while (condition);
How It Works
Unlike a while loop that checks the condition first, the do...while loop executes the block once before checking the condition. It’s a perfect fit for scenarios where an action must occur at least once — like prompting user input, menu systems, or retry logic.
Basic Example
let count = 1;
do {
console.log("Count is: " + count);
count++;
} while (count <= 3);
Count is: 1
Count is: 2
Count is: 3
Explanation
Here, the loop starts with count = 1. It prints the value, then increments it. This continues until count exceeds 3. Since the check comes after the execution, even if count was more than 3 initially, the message would still print once.
When the Condition is Initially False
let count = 5;
do {
console.log("This will run once even though count > 3");
} while (count <= 3);
This will run once even though count > 3
This showcases the beauty — or danger — of do...while. It doesn’t care if the condition fails; the code block will always execute once.
Common Use Case: Validating User Input
let input;
do {
input = prompt("Enter a number greater than 10:");
} while (parseInt(input) <= 10);
console.log("You entered: " + input);
You entered: 15
This code ensures the user enters a number greater than 10 — and keeps prompting until they do. The loop is helpful because the prompt must happen at least once regardless of the input.
Using break and continue with do...while
Breaking the Loop Prematurely
let i = 0;
do {
if (i === 3) {
break;
}
console.log("i is: " + i);
i++;
} while (i < 5);
console.log('end');
i is: 0
i is: 1
i is: 2
end
As soon as i hits 3, the loop is broken using break.
Skipping Iterations with continue
let i = 0;
do {
i++;
if (i === 2) {
continue;
}
console.log("i is: " + i);
} while (i < 4);
console.log('Done!')
i is: 1
i is: 3
i is: 4
Done!
When i equals 2, continue skips that iteration — the print is skipped.
Looping Over Arrays with do...while
const colors = ["red", "green", "blue"];
let index = 0;
do {
console.log("Color:", colors[index]);
index++;
} while (index < colors.length);
Color: red
Color: green
Color: blue
This is a basic array iteration. While not the most common method (we usually use for or forEach), it demonstrates that do...while is flexible.
Infinite Loop Warning
let num = 1;
do {
console.log(num);
// forgot to increment num
} while (num < 5);
1
1
1
This creates an infinite loop because the condition num < 5 is always true and num never changes. Always ensure your loop will reach a stopping condition!
Summary: When to Use do...while
- When the loop body must run at least once.
- When you're collecting input or performing actions before checks.
- When a check is only relevant after execution (post-condition logic).
Key Takeaways
do...whileexecutes at least once before checking the condition.- It's useful for input validation, retry logic, and menu-driven programs.
- Careless use can lead to infinite loops — always control your loop exit.
Recognize the important boundary
The first execution is guaranteed, not an infinite retry guarantee. Include the semicolon after the closing condition.
Try a small variation
JavaScript · original source for practice
let attempts = 0;
do {
attempts++;
} while (false);
console.log(attempts);
Your task: Replace attempts++ with attempts += 2. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The body still runs once, but that execution now adds 2.
JavaScript · complete worked variation
let attempts = 0;
do {
attempts += 2;
} while (false);
console.log(attempts);
Expected output
2Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
let attempts = 0;
do {
attempts++;
} while (false);
console.log(attempts);
Keep the useful idea
A do...while loop executes its body before checking the condition. This is useful for a first attempt that must occur, even when the continuation condition is already false.
Check your variation against this explanation: The body still runs once, but that execution now adds 2.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.