20.4. Control Structures

Like many other languages, JavaScript supports many different control structures that can be used to execute particular blocks of code based on decisions or repeat blocks of code while a particular condition is true. The following sections cover the various control structures available in JavaScript.

20.4.1. Do While

The do while loop executes one or more lines of code as long as a specified condition remains true. This structure has the following format:

do  {
  // statement(s) to execute
} while (<expression>);

Due to the expression being evaluated at the end of the structure, statement(s) in a do while loop are executed at least once. The following example will loop a total of 20 times — incrementing the variable x each time until x reaches the value 20:

var x = 0;
do {
  x++;  // increment x
} while (x < 20);

20.4.2. While

The while loop executes one or more lines of code while a specified expression remains true. The while loop has the following syntax:

while (<expression>) {
  // statement(s) to execute
}

Because the <expression> is evaluated at the beginning of the loop, the statement(s) will not be executed if the <expression> is false at the beginning of the loop. For example, the following loop will execute 20 times, each iteration of the loop incrementing x until it reaches 20:

var x = 0;
while (x <= 20) {  // do until x = 20 (will not execute when x = 21)
  x++;  // increment x
}

20.4.3. For and For In

The for loop executes statement(s) a specific number ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.