While Loops

What are While Loops?

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).

Do While Loops

A do...while loop is a variation that guarantees at least one execution of the loop body because the condition is evaluated after the code block. The syntax for this is to put a while statement inside a do statement.

do {
    code;
} while (condition);

let i = 10;

do {
    console.log(i);
    i++;
} while (i < 5);

In the above example, 10 is logged once because it is executed prior to the while loop and then the condition of the while loop fails.

Break and Continue

The break keyword exits the loop entirely, skipping any remaining iterations.

The continue keyword skips the current iteration, and jumps to the next loop cycle.