Loops are an essential programming construct that allows you to execute a specific piece of code multiple times until a given condition is met. Instead of writing repetitive code, loops enable you to efficiently run a set of instructions for as many times as necessary.
In this post, we’ll focus on the do-while loop in JavaScript, explaining its syntax and usage with practical examples.
The
do-whileloop is particularly useful when you need to ensure that a block of code runs at least once, regardless of the condition.
The do-while Loop in JavaScript
Unlike the for or while loops, the do-while loop always executes the block of code once before checking the condition. This is because the condition is evaluated after the loop body has executed. Here’s the basic syntax of the do-while loop in JavaScript:
do {
statement;
} while (condition);
Here’s a breakdown of what happens behind the scenes:
- The statement (loop body) is executed.
- After the statement is executed, the condition is evaluated. If the condition evaluates to
true, the loop continues and the statement runs again. If the condition evaluates tofalse, the loop terminates.
In contrast to the for and
whileloops, thedo-whileloop guarantees that the loop body executes at least once, regardless of the condition.
Example A: Display a Message 5 Times
In this example, we use a do-while loop to display a message 5 times:
// program to display a message 5 times
let i = 1;
const n = 5;
do {
console.log('I love JavaScript.');
i++;
} while (i <= n);
Output:
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.In this case, the loop runs 5 times, as the value of i is incremented after each iteration and checked against the value of n.
Example B: Displaying Numbers from 1 to 5
Here, we use a do-while loop to print numbers from 1 to 5:
// program to display numbers from 1 to 5
let i = 1;
const n = 5;
do {
console.log(i);
i++;
} while (i <= n);
Output:
1
2
3
4
5In this example, the loop runs as long as i <= 5. Even if the initial value of i had been greater than 5, the loop would still run once before checking the condition.
Key Differences Between while and do-while Loops
The main difference between the while and do-while loops lies in when the condition is checked:
whileloop: The condition is checked at the beginning, before the loop body executes. If the condition isfalseinitially, the loop body will not run.do-whileloop: The loop body executes first, and the condition is checked afterward. This ensures that the loop body runs at least once, even if the condition is initiallyfalse.
Here's an example that demonstrates the difference between the two loops:
Using a while Loop:
let i = 6;
const n = 5;
while (i <= n) {
console.log(i);
i++;
}
Output: (Nothing will be printed since the condition is false initially.)
Using a do-while Loop:
let i = 6;
const n = 5;
do {
console.log(i);
i++;
} while (i <= n);
Output:
6In this case, even though the condition is initially false, the do-while loop executes the loop body at least once, which is why the number 6 is printed.
Example C: Sum of Natural Numbers from 1 to 100
Let's use the do-while loop to calculate the sum of natural numbers from 1 to 100:
// program to display the sum of natural numbers
let sum = 0;
let i = 1;
const n = 100;
do {
sum += i;
i++;
} while (i <= n);
console.log('Sum:', sum);
Output:
Sum: 5050This loop adds the value of i to the sum variable and continues to do so until i reaches 101, at which point the condition fails and the loop stops.
Example D: Using do-while to Validate User Input
The do-while loop is often useful in scenarios where you need to validate user input and ensure that the loop runs at least once before performing the validation.
let number;
do {
number = parseInt(prompt("Enter a number greater than 10:"), 10);
} while (isNaN(number) || number <= 10);
console.log("You entered: " + number);
In this example, the loop prompts the user for input and continues to ask for a number until a valid value greater than 10 is entered. Note the use of parseInt() to convert the string returned by prompt() into an actual number, and the isNaN() check to handle non-numeric input.
Using break and continue in do-while Loops
You can use break to exit a do-while loop early, and continue to skip the rest of the current iteration and jump to the condition check.
Exiting Early with break
let i = 1;
do {
if (i === 3) {
console.log('Stopping at 3');
break;
}
console.log(i);
i++;
} while (i <= 5);
Output:
1
2
Stopping at 3The loop stops as soon as i equals 3, even though the condition would allow it to continue up to 5. For more on the break statement, check out our post on the JavaScript break statement.
Skipping an Iteration with continue
let i = 0;
do {
i++;
if (i === 3) {
continue;
}
console.log(i);
} while (i < 5);
Output:
1
2
4
5The number 3 is skipped because continue jumps directly to the condition check, bypassing the console.log() call for that iteration.
Common Pitfalls to Avoid
When working with do-while loops, watch out for these common mistakes:
1. Forgetting to update the loop variable
If you forget to increment or update the variable used in the condition, the loop will run forever:
// Infinite loop - missing i++
let i = 1;
do {
console.log(i);
// i++ is missing!
} while (i <= 5);
Always make sure the loop variable is updated inside the loop body. An infinite loop can freeze the browser tab or crash your application.
2. Missing the semicolon after the while condition
Unlike the while loop, the do-while loop requires a semicolon after the closing parenthesis:
// Correct
do { ... } while (condition);
// May cause issues
do { ... } while (condition)
While JavaScript's automatic semicolon insertion (ASI) will usually handle this, it's a best practice to always include the semicolon to avoid unexpected behavior.
3. Confusing the loop with a while loop
Remember that the do-while loop always runs at least once. If you need to check the condition before the first iteration, use a while loop instead.
FAQs
do-while loop when you need the code to execute at least once before checking the condition. Common use cases include user input validation, menu-driven programs, and retry logic where you want to attempt an operation first and then check whether it succeeded.break statement exits the loop entirely, and continue skips the rest of the current iteration and jumps directly to the condition check. Both work the same way as in for and while loops.false, the loop will run indefinitely, creating an infinite loop. This can freeze your browser tab or crash your application. Always make sure the loop variable is updated inside the loop body so the condition eventually evaluates to false, or use a break statement to exit the loop under certain conditions.while(condition); required?
while(condition); in a do-while loop. Omitting it can lead to unexpected behavior in edge cases and makes your code less readable.do-while loops inside other loops (including for, while, and other do-while loops). Each loop maintains its own loop variable and condition. Just be careful with deeply nested loops, as they can significantly impact performance and make your code harder to read.Conclusion
The do-while loop in JavaScript is a versatile construct that guarantees at least one execution of the loop body, making it particularly useful for tasks like input validation, retry logic, and menu systems where the condition must be evaluated after running the code.
Understanding the do-while loop, along with other loop types, is critical for efficient coding in JavaScript. If you want to explore more about loops, check out my post on the JavaScript for loop. You might also find our guide to JavaScript arrays helpful, as arrays are one of the most common data structures you'll iterate over with loops.

