Skip to Content


You (Level 0)
0% Complete
Last Badge Earned
None

JavaScript For loops are a little bit complicated, but you really need to understand them. It is a combination of a statement, a condition, and another statement. Typically, for loops iterate through code multiple times known as a loop. The great thing about for loops is that you can program them to run exactly how many times you want. Let's just go ahead and jump into an example.

Example for(var i = 0; i < 5; i++) //statement 1 var i = 0; condition i<5; statement2 i++;
{
document.write(i); //write current value of variable i
document.write('<br/>');
}
document.write(" End of for loop ");
Result
0
1
2
3
4
End of for loop

The for loop is somewhat like a modified if statement that restarts itself until the condition is satisfied. Inside of the for loop we have a statement var i = 0; that declares a variable i and sets it equal to 0. Next, we have the conditional i < 5 that is the if part of the statement. We know that the conditional says if i < 5, then run the statements in the { }. Finally, we have an increment operator statement, i++, which is the most commonly used way to advance a for loop.

Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we print i, document.write(i), for the first time it is 0 rather than 1. So, we run through the statements in the { } and we get the results 0,1,2,3,4. Right after the final execution of statements, i is incremented to 5, which was then compared against the conditional i < 5. It obviously is false at this stage; therefore, we move outside of the for loop and we execute the next line of code that happens to be our document.write(" End of for loop "); statement.

References

Let's explore some more tutorials or topics!

Previous Tutorial Next Tutorial


If you enjoyed this resource, support me by sharing this page with others.

Comment on

  • User

    Ahmed S June 25, 2014, 12:17 a.m.

    I have doubt about the beginning of the third paragraph of JavaScript For Loop: &quot;Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we print i, document.write(i), for the first time it is 0 rather than 1.&quot; I believe that even if we place the ++ before the variable the first printing of 'i' still will print 0 not 1