Languages
[Edit]
EN

JavaScript - for statement

0 points
Created by:
Gaia-Kirby
390

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 for loop are optional (initial-expression, condition-expression and final-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++;
}

References

  1. for - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join