Categories
JavaScript Programming Language

JavaScript For Loop

Loops are handy, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

Example:

for (i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object
  • for/of – loops through the values of an iterable object
  • while – loops through a block of code while a specified condition is true
  • do/while – also loops through a block of code while a specified condition is true

The For Loop

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}