JavaScript Code


JavaScript While Loop


While Loop

while (condition) {
  //code
}

where

  • while is keyword.
  • condition is a boolean expression.
  • code is any valid JavaScript code.

While loop execution starts with the condition evaluation. Ff condition is true, then code inside while loop is executed, and the condition is evaluated again. Ff condition evaluates to false, then while loop execution is completed.

Examples

1. While loop to print 'hello world' 5 times.

let i = 0;
while (i < 5) {
    console.log('hello world');
    i++;
}

2. While loop to find factorial of a number.

let n = 5;
let factorial = 1;

let i = 2;
while (i <= n) {
    factorial *= i;
    i++;
}
console.log(n+'! = '+ factorial);