A JavaScript for
loop has the following four parts:
for (initialization; condition; final-expression) statement
The three expressions separated by a semi-colon, enclosed within parentheses are used to create the loop. Together they form a "for statement". The for statement is followed by a single statement, or a block of statements that are to be executed in the body of the loop. For example:
for (let i = 0; i < 5; i++) { console.log(i); // 0 1 2 3 4 }
All three expressions in the for statement can be omitted (as they're optional). However, in that case, you should update the counter variable yourself and break the loop at some point in the loop's body. If you don't terminate the loop, it will go on infinitely. For example:
let i = 0; for (;;) { if (i >= 5) { break; } console.log(i); // 0 1 2 3 4 i++; }
Following topics describe each part of the loop in detail:
Initialization
This part is typically used to initialize variables. The expressions in this part are evaluated once before the loop begins.
You may omit the initialization part altogether as it's optional. For example:
let i = 0; for (; i < 5; i++) { console.log(i); // 0 1 2 3 4 }
Condition
This is the part where you provide a termination condition for the loop. As long as this condition is true
, the loop will continue executing.
The condition part of the for
loop is optional, and can be omitted. If you omit this part, remember that the condition will always evaluate to true
and you must terminate the loop from within its body (for example by using break
or return
):
for (let i = 0;; i++) { if (i >= 5) { break; } console.log(i); // 0 1 2 3 4 }
Final-Expression
This is the part of the for statement that is evaluated at the end of each loop iteration. Here, typically, the counter variable is updated or incremented/decremented.
The final-expression part of the for
loop is optional, and can be omitted. If you omit the final-expression, then you can update the counter variable within the body of the loop, for example, like so:
for (let i = 0; i < 5;) { console.log(i); // 0 1 2 3 4 i++; }
Statement
A for
loop's body can have a single statement or a block of statements (grouped within curly braces). A statement is executed as long as the condition of the loop evaluates to true
.
You can also specify an empty statement (;
), for example, like so:
const linearCoords = []; for (let i = 0; i < 3; linearCoords.push([i, ++i])); console.log(linearCoords); // [[0,1], [1,2], [2,3]]
Without the semi-colon after the for statement, the line that follows the for
loop will be considered the for
loop's body. Therefore, to execute no statement, it is important to add an empty statement using a semi-colon (;
).
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.