{{jsSidebar("Statements")}}
Summary
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 thewhile
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 andx
= 1 - After the second pass:
n
= 2 andx
= 3 - After the third pass:
n
= 3 andx
= 6
After completing the third pass, the condition n
< 3 is no longer true, so the loop terminates.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition. | Standard | Initial definition. |
{{SpecName('ES5.1', '#sec-12.6.2', 'while statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-while-statement', 'while statement')}} | {{Spec2('ES6')}} |
Browser compatibility
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
See also
do...while
- {{jsxref("Statements/for", "for")}}