while statement
The while construct sets a
loop. A code placed inside it will
be repeated a certain number of
times.
Syntax
while ( while an expression is true ) {
execute this code
};
Example
Let's output numbers from
1 to 10:
let i = 1;
while (i <= 10) {
console.log(i);
i++;
}
Example
Let's output even numbers
from 2 to 10:
let i = 2;
while (i <= 10) {
console.log(i);
i += 2;
}
See also
-
the lesson from JavaScript tutorial
detailing how to work with thewhileloop -
the
forstatement
that also creates a loop -
the
breakstatement
that breaks a loop -
the
continuestatement
that moves a loop to next iteration