JavaScript Code

JavaScript For Loop


For Loop

for (initialisation; condition; update) {
  //code
}
  • for is keyword
  • initialisation is where variables are initialised
  • condition is a boolean expression
  • update is where variables are updated
  • code is any valid JavaScript code

for loop execution starts with initialisation, then condition evaluation. if condition is true, then code inside for loop is executed, then update happens. after update, condition is evaluated, if true, code is execute, and so on. if condition is false, then for loop execution is completed

Examples

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

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

2. for loop to find factorial of a number

n = 5;
factorial = 1;
for (i = 2; i <= n; i++) {
    factorial *= i;
}
console.log(n+'! = '+ factorial);