JS Do While Loop Syntax and Practical Use Cases
The do while loop guarantees the body runs at least once before checking the condition. Learn the syntax, when this behavior matters, and practical real-world use cases.
A do while loop in JavaScript runs its body first, then checks the condition. This guarantees the code inside the loop executes at least once, no matter what the condition evaluates to.
It is the least used of the three JavaScript loop types, but it solves a specific problem that for and while do not: when you need one guaranteed execution before you can decide whether to keep going.
Do While Syntax
The do keyword comes first, followed by the body block. The while keyword and condition come after, with a semicolon at the end:
do {
// body runs at least once
} while (condition);The semicolon after the closing parenthesis is required. Leaving it out does not always cause a syntax error, but it is part of the correct syntax and makes the intent clear.
Here is the smallest working example:
let count = 5;
do {
console.log("Count is:", count);
count++;
} while (count < 3);JavaScript runs the body once before it ever looks at the condition, which is the whole point of this loop type. Output:
Count is: 5Even though count starts at 5 and 5 < 3 is false, the body still runs once. JavaScript executes the body, prints the message, increments count to 6, and then checks the condition. Since 6 is still not less than 3, it stops.
If you wrote the same logic with a regular while loop, nothing would print:
let count = 5;
while (count < 3) {
console.log("Count is:", count);
count++;
}
// No output. The condition is false from the start.Execution Order
Unlike a while loop that checks first, do while runs the body without any precondition. After the body finishes, the condition is evaluated.
If true, it loops back. If false, it moves on. This order is the only structural difference between while and do while, but it changes when you reach for each one.
Validating User Input
The most textbook use case for do while is prompting a user and validating the response. You must show the prompt at least once to get input, and only then can you decide whether to ask again:
let answer;
do {
answer = prompt("Guess a number between 1 and 10:");
answer = Number(answer);
} while (answer < 1 || answer > 10);
console.log("You picked:", answer);The prompt appears at least once. If the user types 15, the condition 15 < 1 || 15 > 10 is true, so the loop repeats and asks again. The loop only exits once the input is a valid number in range.
Without do while, you would need to duplicate the prompt logic -- once before the loop and once inside it. do while removes that duplication.
Menu Systems
Another classic use case is a menu that must be displayed at least once before the user can choose to exit:
let choice;
do {
choice = prompt("Choose an option:\n1. View profile\n2. Edit settings\n3. Exit");
if (choice === "1") console.log("Showing profile...");
else if (choice === "2") console.log("Opening settings...");
} while (choice !== "3");
console.log("Goodbye.");The menu appears at least once. The user can pick options 1 or 2, which run the corresponding code, then the menu shows again. Choosing 3 makes the condition choice !== "3" false, and the loop exits.
Processing Data with a Minimum Guarantee
Sometimes you need to process at least one item from a data source before you even know if more exist:
const queue = ["task1", "task2", "task3"];
do {
const current = queue.shift();
console.log("Processing:", current);
} while (queue.length > 0);
console.log("Queue is empty");Each pass removes and processes one item, then checks if any are left, so the loop keeps going until the queue is empty. Output:
Processing: task1
Processing: task2
Processing: task3
Queue is emptyEach iteration removes the first item with shift() and processes it. After processing, the loop checks if anything remains. The do while structure works here because you want to process the first item without checking whether the queue is empty -- you already know it has at least one.
Do While vs While: Side-by-Side
do while | while | |
|---|---|---|
| First check | After body runs | Before body runs |
| Minimum runs | 1 | 0 |
| Best for | User input, menus, guaranteed first run | Unknown count, optional execution |
| Semicolon | Required after condition | Not used |
let x = 10;
while (x < 5) {
console.log("Never prints");
}
let y = 10;
do {
console.log("Prints once");
} while (y < 5);The behavior difference is clear: while checks the door before entering, do while enters first and checks the door after.
Common Mistakes
Forgetting the semicolon. The semicolon after while (condition) is part of the syntax:
// WRONG: missing semicolon
do {
console.log("Hi");
} while (true)
// RIGHT
do {
console.log("Hi");
} while (true);Using do while when while would be cleaner. If the body does not need to run at least once, use a regular while loop instead. Forcing do where while fits makes readers wonder why the guaranteed execution matters.
Creating an infinite loop with a condition that never turns false. The same rules apply as with the while loop and for loop: something inside the body must move toward the exit condition. Also see the guide on avoiding infinite loops.
For a broader comparison of all three loop types and when to choose each, see the JavaScript loops overview.
Rune AI
Key Insights
- A do while loop runs the body first, then checks the condition.
- The body is guaranteed to execute at least once.
- Use do while when you need a value from the body before you can evaluate the condition.
- Common use cases include user prompts, menu loops, and initial setup followed by conditional repetition.
- Do not forget the semicolon after the while condition.
Frequently Asked Questions
What is the main difference between while and do while?
When should I actually use do while?
Does do while have better performance than while?
Conclusion
The do while loop is the least common but most specific loop in JavaScript. It guarantees one execution before any condition is evaluated. Use it when the body must run at least once, such as user input validation, menu systems, or any situation where you need a result before you can decide whether to repeat.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.