Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Наші волонтери ще не переклали цю статтю мовою: Українська. Приєднайтесь до нас і допоможіть зробити це!

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

Syntax

while (condition) {
  statement
}
condition
An expression evaluated before each pass through the loop. If this condition evaluates to true, statement is executed. When condition evaluates to false, execution continues with the statement after the while loop.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.

Examples

The following while loop iterates as long as n is less than three.

var n = 0;
var x = 0;

while (n < 3) {
  n++;
  x += n;
}

Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Specifications

Specification Status Comment
ECMAScript 2017 Draft (ECMA-262)
The definition of 'while statement' in that specification.
Draft  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'while statement' in that specification.
Standard  
ECMAScript 5.1 (ECMA-262)
The definition of 'while statement' in that specification.
Standard  
ECMAScript 3rd Edition (ECMA-262)
The definition of 'while statement' in that specification.
Standard  
ECMAScript 1st Edition (ECMA-262)
The definition of 'while statement' in that specification.
Standard Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Мітки документа й учасники

Мітки: 
 Зробили внесок у цю сторінку: fscholz, Sebastianz, ziyunfei, Havvy, Sheppy, ethertank, dronov, Mgjbot, Maian, Marcoos, RJacinto
 Востаннє оновлена: fscholz,