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.do-while loop and a while loop in JavaScript?do-while loop behaviordo-while loop executes the code block first, then checks the condition to decide if it should repeat.while loopwhile loop checks the condition before running the code block, so it may not run at all if the condition is false initially.do-while loop runs the code block at least once before checking the condition. -> Option Bdo-while runs once before condition [OK]do-while loop in JavaScript?do-while syntaxdo-while loop starts with do, then the code block in braces, followed by while with the condition in parentheses and a semicolon.let count = 3;
do {
console.log(count);
count--;
} while (count > 0);do-while loop code:let i = 0;
do {
console.log(i);
i++
} while i < 3;while condition syntaxwhile must be inside parentheses. Here, it is written as while i < 3; without parentheses.i++ is allowed in JavaScript (automatic semicolon insertion). Variable i is initialized. Condition does not go inside braces, only parentheses.do-while loop code correctly repeats the prompt until the user enters a valid number?while (num <= 10) - correct condition to reject 10 or less; uninitialized num fine in do-while.while (num < 10) - accepts 10 incorrectly; unnecessary init.while (num < 10) - accepts 10 incorrectly.while (num > 10) - loops when input is valid.Pass the test and this pattern moves unknown