Understanding the JavaScript do...while
Loop
In this post, we’ll explore the do...while
loop in JavaScript—how it guarantees at least one execution, its syntax, and usage examples.
What Is a do...while
Loop?
A do...while
loop runs the code block once first, then repeats as long as the condition is true. Unlike while
, it always executes at least one iteration.
Syntax
1do {
2 // code to run at least once
3} while (condition);
Step-by-Step Example
-
Initialize a variable
-
Write the do...while
loop
1do {
2 console.log("Hello world");
3} while (0 > checker);
-
What Happens
- Executes
console.log("Hello world")
once, even though 0 > checker
is false.
- Checks the condition after the block; because
0 > 1
is false, it stops.
Extended Example with Increment
1let checker = 1;
2
3do {
4 console.log("Current value:", checker);
5 checker++;
6} while (checker < 10);
7
8// Output:
9// Current value: 1
10// Current value: 2
11// ...
12// Current value: 9
- The loop runs first with
checker = 1
.
- After each iteration,
checker
increments by 1.
- Continues until
checker < 10
becomes false (when checker
reaches 10).
Common Pitfalls
- Accidental infinite loops: If the condition never becomes false, the loop will run forever.
1let i = 0;
2do {
3 console.log(i);
4 // missing update
5} while (i < 5);
6// This will run forever!
- Off-by-one: Ensure the condition correctly matches your intended range.
When to Use a do...while
Loop
- When you need the code to run at least once regardless of the condition.
- When post-condition evaluation makes your logic clearer.
Summary
do...while
ensures the loop body runs at least one time.
- The condition is evaluated after each iteration.
- Always manage loop variables to prevent infinite loops.