While a for loop is ideal when you know in advance how many times you need to iterate, while and do...while loops are designed for situations where iteration depends on dynamic conditions (e.g. waiting for user input, reading chunks from a stream, or rolling dice until a 6 appears).
1. The while Loop: Pre-Test Loop
The while loop evaluates its condition before executing the code block. If the condition is initially false, the code block never runs at all!
1 [ Evaluate Condition ]
2 |
3 +--------+--------+
4 | true | false
5 v v
6[ Execute Body ] [ Exit Loop ]
7 |
8 +---> [ Re-evaluate Condition ]
Syntax:
1while(condition){
2// Code executed while condition remains true
3}
Practical Example: Game Loop Simulation
1let health =100;
2let round =1;
3
4while(health >0){
5const damage = Math.floor(Math.random()*30)+10;
6 health -= damage;
7 console.log(`Round ${round}: Player took ${damage} damage. Health left: ${Math.max(0, health)}`);
8 round++;
9}
10
11console.log("Game Over! Player has been defeated.");
2. The do...while Loop: Post-Test Loop
The do...while loop evaluates its condition after executing the code block.
[!IMPORTANT]
A do...while loop is guaranteed to execute at least ONCE, even if the condition is false from the very beginning!
1[ Execute Body First ]
2 |
3 v
4[ Evaluate Condition ]
5 |
6 +--------+--------+
7 | true | false
8 v v
9[ Loop repeats ] [ Exit Loop ]
Syntax:
1do{
2// Executes at least once!
3}while(condition);
Practical Example: User Prompt Validation
1let password;
2
3do{
4 password =prompt("Enter a password with at least 6 characters:");
5}while(!password || password.length <6);
6
7console.log("Password accepted!");
3. Comparison: while vs do...while
1let count =10;
2
3// The while loop NEVER runs:
4while(count <5){
5 console.log("This will never print!");
6}
7
8// The do...while loop runs ONCE:
9do{
10 console.log("This prints exactly once!");// Prints!
11}while(count <5);
Loop Type
When Condition is Tested
Minimum Execution Count
while
Before the loop body (Pre-test)
0
do...while
After the loop body (Post-test)
1
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
What is the primary operational difference between a while loop and a do...while loop?
Question 2
How many times will let x = 5; while (x < 3) { x++; } execute?
Question 3
How many times will let y = 5; do { y++; } while (y < 3); execute?
Question 4
What must you ensure occurs inside the body of a while loop to prevent an infinite loop?
Question 5
For which scenario is a do...while loop ideal?
Next Lesson
Loop Control: break, continue
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.