EN
JavaScript - for statement
0
points
In this article, we would like to show you for statement to create loops in JavaScript.
Syntax
for ([initial-expression]; [condition-expression]; [final-expression]) {
// statement
}
Note:
All three expressions in the head of the
forloop are optional (initial-expression,condition-expressionandfinal-expression). For more details see the examples below.
Practical examples
Example 1
In this example, we declare i variable and initialize it with 0. the for statement checks if i is less than 3, performs the statement inside the braces and increments i by 1 after each pass through the loop.
// ONLINE-RUNNER:browser;
for (let i = 0; i < 3; ++i) {
console.log(i);
}
Example 2
In this example, we skip the initial-expression in the head of the for loop.
// ONLINE-RUNNER:browser;
let i = 0
for (; i < 3; ++i) {
console.log(i);
}
Example 3
In this example, we omit the condition-expression.
// ONLINE-RUNNER:browser;
for (let i = 0; ; i++) {
console.log(i);
if (i > 3) break;
}
Example 4
In this example, we omit all three blocks.
// ONLINE-RUNNER:browser;
let i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}