JavaScript for Loop
JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.
for(initializer; condition; iteration)
The for loop requires following three parts.
- Initializer: Initialize a counter variable to start with
- Condition: specify a condition that must evaluate to true for next iteration
- Iteration: increase or decrease counter
for (var i = 0; i < 5; i++)
{
console.log(i);
}
0 1 2 3 4
In the above example, var i = 0 is an initializer statement where we declare a variable i with value 0. The second part, i < 5 is a condition where it checks whether i is less than 5 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.
var arr = [10, 11, 12, 13, 14];
for (var i = 0; i < 5; i++)
{
console.log(arr[i]);
}
10 11 12 13 14
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.
var arr = [10, 11, 12, 13, 14];
var i = 0;
for (; ;) {
if (i >= 5)
break;
console.log(arr[i]);
i++;
}
10 11 12 13 14
Learn about while loop in the next section.
- JavaScript for loop is used to execute code repeatedly.
- for loop includes three parts: initialization, condition and iteration. e.g.
for(initializer; condition; iteration){ ... }
- The code block can be wrapped with { } brackets.
- An initializer can be specified before starting for loop. The condition and increment statements can be included inside the block.