JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.
Example of for loop:
for (var i = 0; i < 6; i++)
{
console.log(i);
}
output:
0 1 2 3 4 5
In the above example, var i = 0 is an initializer statement where we declare a variable i with value 0. The second part, i < 6 is a condition where it checks whether i is less than 6 or not. The third part, i++ is iteration statement where we use ++ operator to increase the value of i to 1. All these three parts are separated by semicolon ;.
The for loop can also be used to get the values for an array.
Example of for loop:
var arr = [20, 21, 22, 23, 24];
for (var i = 0; i< 5; i++)
{
console.log(arr[i]);
}
output:
20 21 22 23 24
Please note that it is not mandatory to specify an initializer, condition and increment expression into bracket. You can specify initializer before starting for loop. The condition and increment statements can be included inside the block.
Example of for loop
var arr = [10, 11, 12, 13, 14];
var i = 0;
for (; ;) {
if (i == 5)
break;
console.log(arr[i]);
i++;
}
output:
10 11 12 13 14