JavaScript Code

JavaScript While Loop


While Loop

while (condition) {
  //code
}
  • while is keyword
  • condition is a boolean expression
  • code is any valid JavaScript code

while loop execution starts with the condition evaluation. if condition is true, then code inside while loop is executed, and the condition is evaluated again. if 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);