JavaScript While Loop
A `while` loop repeats a block of code as long as a condition remains true, checking the condition before each iteration. It is ideal when the number of repetitions isn't known in advance.
A `do...while` loop is similar but always executes the body at least once, since it checks the condition after running the block.
while loop
`while (condition) { ... }` checks the condition first; if false immediately, the body never runs.
do...while loop
`do { ... } while (condition);` guarantees the body runs at least once before checking the condition.
let i = 0;
while (i < 3) {
console.log(i);
i++;
}0
1
2The loop checks i < 3 before every iteration.
let i = 5;
do {
console.log(i);
i++;
} while (i < 3);5do...while runs once even though the condition is false immediately.
Key points
- while checks its condition before running the loop body.
- do...while always runs at least once.
- Both loops need a way to eventually make the condition false.
- Use while when the number of iterations is unknown ahead of time.
