JavaScript do...while: Execute Before Testing
Quick answer
A do...while loop executes its body before checking the continuation condition. It therefore enters the body at least once when execution reaches the loop normally.
How it works
Write do { ... } while (condition);. This structure suits a first attempt that must happen before deciding whether another is necessary. If the first execution already satisfies the stopping condition, the loop ends after that first body. As with while, body updates must ensure progress.
let attempts = 0;do { attempts++; } while (false);console.log(attempts);Expected output in Node.js:
1Even a false test is checked after the first body.
let number = 0;do { console.log(number); number += 2; } while (number < 5);Expected output in Node.js:
024The body emits 4 before the update makes number 6.
Common mistakes
Do not choose do...while when zero executions should be allowed. A required first attempt must be part of the task contract, not an accident.
Practice
Return the number of attempts if the process always tries once and stops when attempts reaches the supplied minimum.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript do...while: Execute Before Testing — Knowledge Check
Apply the taught concept and reason about the result.
How many times does do { n++; } while(false) increment n?
Where does do...while evaluate its condition?
What is printed by let n=0; do { n+=2; } while(n<5); console.log(n); ?
Which loop is better when a false initial test must allow zero attempts?
Which is the normal do...while syntax?