JavaScript for loop
Loops can execute a block of code a specified number of times.
JavaScript Loops
If you want to run the same code over and over again, with different values each time, it is convenient to use a loop.
We can output the values of an array like this:
General syntax:
Using the for loop
Try it yourself »
Different types of loops
JavaScript supports different types of loops:
- for- Loop through a block of code a specified number of times
- for/in- Loop through the properties of an object
- while- Loop through a block of code while a specified condition is true
- do/while- Also loop through a block of code while a specified condition is true
For Loop
The for loop is a tool you will often use when you want to create a loop.
The following is the syntax of the for loop:
{
Code block to be executed
}
Statement 1Executed before (the code block) starts
Statement 2Defines the condition for running the loop (the code block)
Statement 3Executed after the loop (the code block) has been executed
From the example above, you can see:
Statement 1 sets the variable (var i=0) before the loop starts.
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) after each time the code block has been executed.
Statement 1
Usually we use Statement 1 to initialize the variable used in the loop (var i=0).
Statement 1 is optional, meaning you can omit Statement 1.
You can initialize any value (or multiple values) in Statement 1:
Example:
Try it yourself »
You can also omit Statement 1 (for example, when the value has already been set before the loop starts):
Example:
Try it yourself »
Statement 2
Usually Statement 2 is used to evaluate the condition of the initial variable.
Statement 2 is also optional.
If Statement 2 returns true, the loop starts again; if it returns false, the loop ends.
| If you omit Statement 2, you must provide abreakbreak. Otherwise the loop will not stop. This may crash the browser. Please read about break in a later chapter of this tutorial. |
Statement 3
Usually Statement 3 increments the value of the initial variable.
Statement 3 is also optional.
Statement 3 has multiple uses. The increment can be negative (i--), or larger (i=i+15).
Statement 3 can also be omitted (for example, when there is corresponding code inside the loop):
Example:
Try it yourself »
For/In Loop
The JavaScript for/in statement loops through the properties of an object:
Example
Try it yourself »
You will learn more about the for/in loop in the chapter on JavaScript objects.
While Loop
We will explain the while loop and the do/while loop in the next chapter.
Other Extensions