The While Loop: To the Bitter End
The while loop is the simplest and most intuitive. It just repeats the code as long as the condition is true.
1. Syntax
let i = 0;
while (i < 3) {
alert(i);
i++;
}
2. Shorthand
Any expression can be a condition. JS simply coerces it to a boolean.
let i = 3;
while (i) { // While i is not 0
alert(i--);
}
Warning
Infinite Loop: If the condition always remains true (e.g., you forgot i++), the browser will freeze. Modern browsers can " kill " such tabs, but it's better not to let it get to that point.
Tip
If the loop body consists of a single line, curly braces can be omitted: while (i) alert(i--);.