For Loop

For Loop Syntax

In javascript, a for loop will repeat as long as the specified condition is met. When a for loop is executed, it follows the below steps:-

  1. First the startExpression will be executed.
  2. It will then evaluate the condition. if the condition is met then the loop will continue. If the condition evaluates to false, then the loop will end.
  3. If the condition was met, then the code statements will execute.
  4. After the code statements are executed, the incrementExpression is then executed. After this, it goes back up to step B

for ([startExpression]; [condition]; [incrementExpression])
{
    code statements
}

Example

Below is a for loop in which the start expression sets i equal to 1. It then sets the condition to i <= 10 which will make the loop run as long as i is less than or equal 10. The increment expression is i++ which will add 1 to i after each pass. The code statement just prints out value of i. So this for loop will display 1 though 10 and then end once value of i becomes 11.

var i = 0;
for (i = 1; i <= 10; i++)
{
    document.write(i + "<br>");
}

The above example will have the below output:

1
2
3
4
5
6
7
8
9
10