In JavaScript, while loops allow you to execute a block of code repeatedly as long as a specified condition evaluates to true. They're useful when the number of iterations isn't known beforehand, such as when reading user input or waiting for a certain state. They generally look like the following.
while (condition) {
code;
}
// An example of logging numbers 1-10 as a while loop
let i = 1;
while (i < 11) {
console.log(i);
i++;
}
In the example above:
- The temporary variable, i, starts at 1.
- The condition i < 10 is checked.
- If true, it logs i and increments it by 1.
- This continues until i reaches 11 (which fails the condition).