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.
while (condition) statement
condition
statement
is executed. When condition evaluates to false, execution continues with the statement after the while
loop.statement
{ ... }
) to group those statements.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:
n
= 1 and x
= 1n
= 2 and x
= 3n
= 3 and x
= 6After completing the third pass, the condition n
< 3 is no longer true, so the loop terminates.
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) |
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while