while statement

The while construct sets a loop. A code placed inside it will be repeated a certain number of times.

Syntax

javascriptwhile ( while an expression is true ) {
  execute this code
};

Example

Let's output numbers from 1 to 10:

javascriptlet i = 1;

while (i <= 10) {
  console.log(i);
  i++;
}

Example

Let's output even numbers from 2 to 10:

javascriptlet i = 2;

while (i <= 10) {
  console.log(i);
  i += 2;
}

See also