The “do while” loop in JavaScript runs code once before checking the condition. Use it when the code must run first, then decide if it should repeat.
Table of Content
In this article, you will cover how do while loop works in JavaScript with examples.
What is a do while loop in JavaScript?
The do…while loop runs a block of code first. Then it checks the condition to see if it should repeat. It runs again if the condition is true. Otherwise, it stops.
do {
// Code to execute
} while (condition);
Here is how it works:
- Code to execute: This is the block that runs with each loop cycle.
- Condition: This is the expression checked after each run. The loop repeats if it’s true and stops if it’s false.
Here’s a basic example of a do...while
loop:
let counter = 0;
do {
console.log(counter);
counter++;
} while (counter < 5);
Output:
0
1
2
3
4
The loop runs and prints the value of the counter (0 to 4) to the console. The condition (counter < 5) checks after each iteration, but the loop runs at least once even if the condition is false.
How do...while
Differs from while
and for
Loops?
while
loop: The while
loop checks the condition before it executes the code block. The code inside the loop never executes if the condition is false.
Example of a while
loop:
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}
Output:
0
1
2
3
4
If counter
is 0
, this will behave similarly, but with a critical difference: if the condition is false
at the start, the loop won’t run even once.
for
loop: A for loop is used when the number of iterations is known. It gives more control because it includes:
- Initialization
- Condition check
- Increment or decrement
All of that in one statement.
Example:
for (let counter = 0; counter < 5; counter++) {
console.log(counter);
}
Output:
0
1
2
3
4
So, when to use do while over other loops?
Use do...while
when:
- You need the code to run at least once before the condition check.
- You deal with user input or interactive processes that must run at least once.
The break and continue in do while
In a do...while
loop, you can control the flow of execution with the break
and continue
statements. These allow you to either exit the loop early or skip to the next iteration.
The break statement:
The break
statement is used to exit the loop immediately, regardless of the loop’s condition. When break
is encountered, the program jumps to the first line of code after the loop.
let counter = 0;
do {
if (counter === 3) {
break; // Exit the loop when counter reaches 3
}
console.log(counter);
counter++;
} while (counter < 5);
Output:
0
1
2
In this example, the loop will print 0
, 1
, and 2
to the console. When counter
reaches 3, the break
statement is executed, and the loop is exited.
The continue statement:
The continue
statement is used to skip the current iteration and move to the next one. The loop will check the condition after the current iteration and decide whether to continue or stop.
let counter = 0;
do {
counter++;
if (counter === 3) {
continue; // It skips counter when reach 3
}
console.log(counter);
} while (counter < 5);
Output:
1
2
4
5
The loop prints 1, 2, 4, and 5. When the counter reaches 3, the continue statement executes, skips 3, and moves to the next iteration.
So,
- The
break
stops the loop right away. continue
skips the current iteration and moves to the next one.
Infinite loops and how to avoid them
An infinite loop happens when the loop’s exit condition is never satisfied. This can occur for a few reasons:
- The loop condition is always true.
- There is no code inside the loop to change the condition.
- The condition is incorrectly set and can never evaluate to
false
.
Here’s an example of a do...while
loop that will run forever:
let counter = 0;
do {
console.log(counter);
// No change to the condition, so the loop never stops
} while (counter < 5);
The output is an infinite loop.
In this case, since counter
is never updated inside the loop, the condition (counter < 5
) always remains true
. It causes the loop to run indefinitely.
So, how to avoid that?
Make sure the loop includes code that eventually makes the condition false. For example, increase a counter variable. You can also update a flag value.
let counter = 0;
do {
console.log(counter);
counter++; // Increment counter to eventually exit the loop
} while (counter < 5);
The condition must have a clear endpoint. If you use input from outside the loop or depend on external variables, make sure they eventually cause the condition to return false.
Sometimes, you need to exit the loop early based on logic. Use the break
statement when something goes wrong. This prevents the loop from continuing forever.
let counter = 0;
do {
console.log(counter);
counter++;
if (counter === 10) {
break; // Exit the loop if counter reaches 10
}
} while (counter < 5);
Set a maximum number of iterations to avoid endless loops while testing. You can use a counter limit or a timeout.
let counter = 0;
let maxIterations = 1000;
do {
if (counter >= maxIterations) {
console.log("Exceeded maximum iterations");
break;
}
console.log(counter);
counter++;
} while (counter < 5);
Nested do while loops
A nested do-while
loop places one loop inside another. This helps in complex cases. You can use it with multi-dimensional data. You can also use it in repeated steps inside a main process.
The general format looks like this:
do {
// Outer loop code
do {
// Inner loop code
} while (conditionForInnerLoop);
} while (conditionForOuterLoop);
Here is how this works:
- The outer loop runs first, then the inner loop runs completely for each iteration of the outer loop.
- The condition for the inner loop is checked after each iteration of its block.
- The outer loop condition is checked after each full iteration of the inner loop.
For example:
let outerCounter = 0;
do {
console.log(`Outer loop iteration: ${outerCounter}`);
let innerCounter = 0;
do {
console.log(` Inner loop iteration: ${innerCounter}`);
innerCounter++;
} while (innerCounter < 3);
outerCounter++;
} while (outerCounter < 2);
Output:
Outer loop iteration: 0
Inner loop iteration: 0
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 1
Inner loop iteration: 0
Inner loop iteration: 1
Inner loop iteration: 2
How it works:
- The outer loop runs twice (
outerCounter < 2
). - For each iteration of the outer loop, the inner loop runs three times (
innerCounter < 3
). - The inner loop completes fully before the outer loop continues to its next iteration.
Examples
Input validation within do while:
let userInput;
do {
userInput = prompt("Please enter a number greater than 0:");
} while (isNaN(userInput) || userInput <= 0);
console.log("Valid input:", userInput);
Here is how it works:
The
function asks the user for input. The loop will keep asking the user for a valid number until the input is a number greater than 0.prompt()
- The
do...while
loop checks whether the input is a number (isNaN()
) and whether it’s greater than 0.- If the input is invalid (either not a number or less than or equal to 0), the loop will repeat and ask for input again.
- The loop exits once the user provides valid input, and the valid input is printed.
Combine do-while with condition flags:
let userInput;
let isValidInput = false;
do {
userInput = prompt("Please enter a positive number:");
// Check if the input is a valid positive number
if (!isNaN(userInput) && userInput > 0) {
isValidInput = true;
} else {
alert("Invalid input. Please try again.");
}
} while (!isValidInput);
console.log("Valid input received:", userInput);
- The Condition Flag (
isValidInput
) is used to track whether the input is valid.- It is set to
false
. - The loop continues until the input is a positive number (i.e., when the flag is set to
true
).
- It is set to
- The
do...while
loop runs as long as theisValidInput
flag isfalse
. It makes sure the user keeps being prompted for a valid input.
Wrapping Up
You learned what the do...while
loop is in JavaScript and how it differs from other types of loops like while
and for
. Here is a quick recap:
do...while
runs the loop body once before checking the condition, making it ideal when at least one execution is required—such as prompting for user input.- It’s different from
while
andfor
loops, which check the condition before executing the loop body. - You saw how to use
break
to exit early andcontinue
to skip an iteration within ado...while
loop. - You learned about infinite loops, what causes them, and how to avoid them with condition updates or maximum iteration checks.
- We also explored nested
do...while
loops for handling multi-level processes. - Finally, we looked at real-world use cases, like input validation using condition flags and loop repetition until valid user input is received.
FAQ’s
What is a do...while loop in JavaScript?
When should I use a do...while loop over other loops?
- You need the code to execute at least once before checking the condition.
- You are working with user input or interactive processes that must run at least once.
Can I use break and continue in a do...while loop?
- break: Exits the loop immediately, regardless of the condition.
- continue: Skips the current iteration and moves to the next one.