JavaScript for Loop
The JavaScript for loop is a control flow statement. The for loop is used to execute a code block repeatedly until a certain condition is true. The for loop is also known as for statement.
In general, for loops are used when the number of iterations are already known.
The general form of JavaScript for loop is:
for (initialization; condition; afterthought)
// loop body;
The loop body is either a simple one line statement or code block enclosed by braces {}.
The order of execution of tasks in for loop is as follow:
- Initialization statement:
- This is used to declare and initialize one or more loop counters or loop variables.
- This section is executed only once, before the start of the loop.
- Condition:
- The condition expression evaluates a certain test condition.
- If the condition is true, code inside the loop body is executed.
- If the condition is false, the loop exits.
- If the condition expression is omitted, the condition is considered as true.
- Afterthought:
- Control is transferred to this section after execution of the code in loop body.
- Next, control is transferred to the condition section.
- The loop is repeated if the condition is true.
- The loop exits if the condition is false.
Following is a simple for loop counter example.
// Example - Simple for loop
for(let i=0; i<3; i++){
console.log(i);
}
// Output:
// 0
// 1
// 2
- The loop variable i is initialized to 0.
- The value of loop variable i is evaluated, if it is less than 3. Condition is true, control is transferred to the statement in the loop body.
- Statement in the loop body is executed. Once execution is completed, control is transferred to afterthought section.
- The loop variable i is incremented (i++).
- The condition is evaluated, if the value of i is less than 3, control is transferred to the statement in the loop body.
This flow will continue, unless the test condition is false. Once the test condition evaluates to false, loop exits.