JavaScript While Loop

Loops can execute a block of code as long as a specified condition is true.

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition) {
  // code block to be executed
}

Example

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10 :

Example

while (i < 10) {
  text += "The number is " + i;
  i++;
}

If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.

Continue reading JavaScript While Loop