Loops can execute a block of code a number of times.
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:
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
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.
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Normally you will use statement 1 to initiate the variable used in the loop (var i = 0).
You can initiate many values in statement 1 (separated by comma):
And you can omit statement 1 (like when your values are set before the loop starts):
Often statement 2 is used to evaluate the condition of the initial variable.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
|If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.|
Often statement 3 increases the initial variable.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
The while loop and the do/while loop will be explained in the next chapter.