JavaScript while Loop
Example
Loop a code block as long as a i is less than 5:
let i = 0;
while (i < 5) {
text += i + "<br>";
i++;
}
Loop (iterate over) an array to collect car names:
let text = "";
let i = 0;
while (i < cars.length) {
text += cars[i] + "<br>";
i++;
}
- The loop starts in position 0 (
let i = 0
). - The loop increments
i
for each run (i++
). - The loop runs as long as
i < cars.length
.
More examples below.
Description
The while
statement creates a loop (araund a code block) that is executed while a condition is
true
.
The loop runs while the condition is true
. Otherwise it stops.
See Also:
JavaScript Loop Statements
Syntax
code block to be executed
}
Parameters
The condition for running the code block. If it returns true, the code clock will start over again, otherwise it ends.
Note
If the condition is always true, the loop will never end. This will crash your browser.
If you use a variable in the condition, you must initialize it before the loop, and increment it within the loop. Otherwise the loop will never end. This will also crash your browser.
More Examples
Loop over an array in descending order (negative increment):
let text = "";
let len = cars.length;
while (len--) {
text += cars[len] + "<br>";
}
Using break - Loop through a block of code, but exit the loop when i == 3:
let i = 0;
while (i < 5) {
text += i + "<br>";
i++;
if (i == 3) break;
}
Using continue - Loop through a block of code, but skip the value 3:
let i = 0;
while (i < 5) {
i++;
if (i == 3) continue;
text += i + "<br>";
}
Browser Support
while
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |