May 06, 2021 JavaScript
Loops can execute blocks of code a specified number of times.
If you want to run the same code over and over again, with different values each time, it's convenient to use loops.
We can output the value of the array like this:
JavaScript supports different types of loops:
For loops are tools that you often use when you want to create loops.
Here's the syntax for the loop:
Statement 1 (block of code) starts before it begins.
Statement 2 defines the conditions under which a loop (block of code) is run
Statement 3 is executed after the loop (block of code) has been executed
From the example above, you can see:
Statement 1 sets the variable (var i=0) before the loop begins.
Statement 2 defines the conditions under which the loop runs (i must be less than 5).
Statement 3 adds a value (i)) each time the block of code has been executed.
Typically, we use the variable used in the initialization loop in statement 1 (var i=0).
Statement 1 is optional, which means that statement 1 is not used.
You can initialize any (or more) values in statement 1:
You can also omit statement 1 (for example, when a value has been set before the loop begins):
Typically statement 2 is used to evaluate the conditions of the initial variable.
Statement 2 is also optional.
If statement 2 returns true, the loop starts again, and if false is returned, the loop ends.
If you omit statement 2, you must provide break within the loop. O therwise the cycle cannot stop. T his can cause the browser to crash. Read about break later in this tutorial. |
Typically, statement 3 increases the value of the initial variable.
Statement 3 is also optional.
Statement 3 has several uses. The increment can be negative (i--), or larger (i-i-15).
Statement 3 can also be omitted (for example, when there is code inside the loop):
The JavaScript for/in statement loops through the properties of the object:
Tip: In
JavaScript, the for in loop can traverse not only the properties of the object, but also the array.
You'll learn more about the for/in loop in the section on JavaScript objects.
We'll show you the while loop and the do/while loop in the next chapter.
Cycle iterations with for statements
You can execute code multiple times with a for-loop statement.
Reverse iteration using the for loop
The for loop can iterate in reverse, as long as we define the right conditions.