The best JavaScript for loop Tutorial In 2024, In this tutorial you can learn JavaScript cycle,General wording:,Using for loop,Different types of cycle,For loop,Examples,Statement 1,Example:,Example:,Statement 2,Statement 3,Example:,For / In cycle,Examples,While loop,
The cycle can execute a block of code a specified number of times.
If you want to run over and over again the same code, and each of the values are different, then the use of the cycle is very convenient.
We can output an array of values:
JavaScript support different types of loops:
for loop is that you want to create a loop often used tool.
Here is the syntax for loop:
Statement 1 (block) starts before you begin.
Statement 2 defines the operating cycle (block) conditions
3 statement after the loop (block) has been doing
From the example above, you can see:
Statement 1 set the variable before the loop starts (var i = 0).
Statement 2 defined conditions Cycle run (i must be less than 5).
Statement 3 increased by a value (i ++) after each block of code has been executed.
Normally we would use a statement to initialize the variables used in the cycle (var i = 0).
1 statement is optional, that is not used can also be a statement.
You can initialize any statement 1 (or more) values:
And you can also omit a statement (such as in the beginning of the loop has been set value):
Statement 2 conditions generally used to assess the initial variables.
2 The same statement is optional.
2 If the statement returns true, then the cycle starts again if it returns false, the loop will end.
If you omit the statement 2, it must provide a break in the cycle. Otherwise, the cycle will not be able to stop. This makes it possible to make the browser to crash. Please read about the break in a later section of this tutorial. |
3 statements generally increases the value of the original variable.
Statement 3 is also optional.
Statement 3 has a variety of uses. Increment can be negative (i--), or more (i = i + 15).
Statement 3 may be omitted (eg inside the loop when there is a corresponding code):
JavaScript for / in statement to loop through object properties:
You will learn more about in the section on JavaScript for object / in the knowledge cycle.
We will explain to you while loop and do / while loop in the next chapter.