Concept Flow - Do–while loop
Start
Execute loop body
Check condition
Yes| No
Repeat
The do–while loop runs the code inside the loop first, then checks the condition. If true, it repeats; if false, it stops.
let count = 1; do { console.log(count); count++; } while (count <= 3);
| Step | count before body | Action | count after body | Condition (count <= 3) | Loop continues? |
|---|---|---|---|---|---|
| 1 | 1 | Print 1, increment count to 2 | 2 | 2 <= 3 | Yes |
| 2 | 2 | Print 2, increment count to 3 | 3 | 3 <= 3 | Yes |
| 3 | 3 | Print 3, increment count to 4 | 4 | 4 <= 3 | No |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| count | 1 | 2 | 3 | 4 | 4 |
do {
// code to run
} while (condition);
- Runs loop body first, then checks condition.
- Repeats if condition is true.
- Always runs at least once.