JavaScript Tutorial – For Loop

You should use loop if you want to execute the same code multiple times.

For Loop

For Loop Syntax

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

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

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

For Loop example

<script type="text/javascript">
for (i = 0; i < 3; i++) {
   document.write("Current value of i: " + i + "<br>");
}
</script>
Try it yourself »

Statement 1 of For Loop

Usually statement 1 is used to initiate the variable (counter) used in the for loop. In the above example, variable i is declared and initiated to 0.

Statement 1 is optional, you can define the variable before the for loop starts.

For loop with omitted statement 1

<script type="text/javascript">
var i = 0;
for (; i < 3; i++) {
   document.write("Current value of i: " + i + "<br>");
}
</script>

Statement 2 of For Loop

Statement 2 is used to decide when to end the loop. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.

In the example above, the loop will only end when i < 3 returns false, where i starts at 0. So it will end when i = 3.

Statement 3 of For Loop

Statement 3 is used to help statement 2 to return true so the loop can end.

In the example above, statement 3 increments I by 1. i++ is the same as i = i + 1.

Statement 3 is optional, you can change the value of the variable inside the loop.

For loop with omitted statement 3

<script type="text/javascript">
var i = 0;
for (; i < 3;) {
   document.write("Current value of i: " + i + "<br>");
   i++;
}
</script>