JavaScript includes the while loop to execute a block of code repeatedly as long as a specified condition remains true.
A while loop repeatedly executes a block of code until the specified condition becomes false.
It is useful when the number of iterations is not known in advance.
The loop continues until the condition evaluates to false.
0 1 2 3 4
| Step | Description |
|---|---|
| 1 | Initialize variable before loop |
| 2 | Check condition |
| 3 | Execute code block |
| 4 | Update variable |
| 5 | Repeat until condition becomes false |
1 2 3 4 5 6 7 8 9 10
A while loop can be used to access array elements.
10
20
30
40
50
Always update the counter variable inside the while loop.
This creates an infinite loop because the value of i never changes.
JavaScript provides another variation called the do...while loop.
The do...while loop executes the code block first and checks the condition afterwards.
Therefore, the code block executes at least one time.
0 1 2 3 4
Even if the condition is false, the code block runs once.
5
The loop executes once before checking the condition.
| While Loop | Do While Loop |
|---|---|
| Condition checked first | Condition checked last |
| May execute zero times | Executes at least once |
| Entry controlled loop | Exit controlled loop |
A while loop can be used to count students present in a classroom.
Student 1
Student 2
Student 3
Student 4
Student 5
| Loop Type | Condition Check |
|---|---|
| while | Before execution |
| do...while | After execution |
Which loop executes at least one time even if the condition is false?