For Loop
In JavaScript, For loop statement is used to execute a block of code repeatedly based on a condition.
Syntax
The syntax of For loop statement in JavaScript is
for (initialisation; condition; update) {
//code
}
where
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. In the following program, we use For loop to print 'hello world'
5 times.
for (i = 0; i < 5; i++) {
console.log('hello world');
}
2. In the following program, we use For loop to find factorial of a number.
n = 5;
factorial = 1;
for (i = 2; i <= n; i++) {
factorial *= i;
}
console.log(n+'! = '+ factorial);