This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

while

Summary

Executes a statement or series of statements while a specified condition is true.

Syntax

while ( expression ) {
  statements
}
expression
Required. A Boolean expression that is checked before each iteration of the loop. If expression is true, the loop is executed. If expression is false, the loop is terminated.
statements
Optional. One or more statements to be executed if expression is true.

Examples

var i = 0;

while (i < 5) {
  console.log("This runs 5 times");
  i++;
}
var i = 0;

while (i < 100) {
  if (i == 5) {
    // Stop the while loop early
    break;
  }
  console.log("This happens 5 times");
  i++;
}

Usage

 The while statement checks the expression before a loop is first executed. If expression is false at this time, the loop is never executed.

The while statement keeps iterating until the conditional expression returns false, or encounters a break statement.

It’s essential that the expression can become false or that that loop is terminated with the break statement to prevent an infinite loop.

See also

Other articles

Specification

Attributions

  • Microsoft Developer Network: Article