Do-While Loop
A do-while loop in JavaScript works like a while loop but always executes the code at least once, even if the condition is false initially. It then keeps running as long as the condition is true.
Syntax
do {
// Code block to be executed
} while (condition);Example: Counting from 1 to 5
let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);Output:
1
2
3
4
5Parameters
-
statement
A statement that is executed at least once and re-executed as long as the condition evaluates totrue.
You can use a block statement ({ ... }) to execute multiple statements. -
condition
An expression evaluated after each pass through the loop.
If this condition evaluates totrue, the statement is re-executed.
When the condition evaluates tofalse, execution continues with the statement after thedo...whileloop.
Description
Like other looping statements, you can use control flow statements inside do...while:
breakstops statement execution and goes to the first statement after the loop.continuestops the current iteration and re-evaluates the condition for the next pass.
The
do...whilestatement syntax requires a semicolon at the end, but JavaScript’s automatic semicolon insertion (ASI) might add one if it's missing.
Comparison Between While and Do-While Loop
| While Loop | Do-While Loop |
|---|---|
| It is an entry condition looping structure. | It is an exit condition looping structure. |
The number of iterations depends on the condition mentioned in the while block. | Irrespective of the condition mentioned in the do-while block, there will be a minimum of 1 iteration. |
| The block control condition is available at the starting point of the loop. | The block control condition is available at the endpoint of the loop. |