JavaScript - For Loop

The for loop in JavaScript is used to execute code repeatedly for a specific number of times. It allows you to specify a loop counter, a condition for continuing the loop, and a counter update expression.

Syntax:

for (initialization; condition; update) {

  // code to be executed while condition is true

}

The three expressions in the for statement (initialization, condition, update) are executed in the following order:

  1. The initialization expression is executed only once, at the start of the loop.
  2. The condition expression is evaluated before each iteration of the loop. If the condition is true, the code inside the loop will be executed. If the condition is false, the loop will stop.
  3. The update expression is executed after each iteration of the loop.

The for loop is useful when you know beforehand how many times you need to execute the code inside the loop.