for ([initialization]; [condition]; [final-expression]) statement
initialization
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. The result of this expression is discarded.
condition
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement
is excuted.
final-expression
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition
. Generally used to update or increment the counter variable.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... })
to group those statements. To execute no statement within the loop, use an empty statement (;)
.
All three expressions in the head of the for
loop are optional.
For example, in the initialization
block is not required to initialize variables:
let i = 0;
for (; i < 9; i++) {
console.log(i)
// more statements
}
break
Like the initialization
block, the condition
block is also optional. If you are omitting this expression, you must make sure to break
the loop in the body in order to not create an infinite loop.
for (let i = 0;; i++) {
console.log(i);
if (i > 3) break;
// more statements
}
You can also omit all three blocks. Again, make sure to use a break
statement to end the loop and also modify(increase) a variable, so that the condition for the break
statement is true at some point.
let i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
continue
The continue
statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
continue [label];
label
Identifier associated with the label of the statement.
In contrast to the break
statement, continue
does not terminate the execution of the loop entirely:
Instead,
while
loop, it jumps back to the condition.for
loop, it jumps to the update expression.The continue
statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. In this case, the continue
statement needs to be nested within this labeled statement.
Source:
for - JavaScript | MDN