JavaScript Statements Reference
Loop through a block of code five times:
The result of text will be:
More "Try it Yourself" examples below.
The for statement creates a loop that is executed as long as a condition is true.
The loop will continue to run as long as the condition is true. It will only stop when the condition becomes false.
The for loop is often the tool you will use when you want to create a loop.
JavaScript supports different kinds of loops:
Tip: Use the break statement to break out of a loop, and the continue statement to skip a value in the loop.
Statement | |||||
---|---|---|---|---|---|
for | Yes | Yes | Yes | Yes | Yes |
Parameter | Description |
---|---|
statement1 | Optional. Executed before the loop (the code block) starts. Normally
this statement is used to initialize a counter variable. To
initiate multiple values, separate each value with a comma. Note: This parameter can be omitted. However, do not omit the semicolon ";" |
statement2 | Optional. Defines the condition for running the loop (the code block).
Normally this statement is used to evaluate the condition of the counter
variable. If it returns true, the loop will start over again, if it returns
false, the loop will end. Note: This parameter can be omitted. However, do not omit the semicolon ";". Also, if you omit this parameter, you must provide a break inside the loop. Otherwise the loop will never end, which will crash your browser |
statement3 | Optional. Executed each time after the loop (the code
block) has been executed. Normally this statement is used to increment or
decrement the counter variable. Note: This parameter can be omitted (e.g. to increase/decrease values inside the loop) |
JavaScript Version: | 1.0 |
---|
Loop through the indices of an array to collect the car names from the cars array:
Example above explained:
Initiate multiple values in the first parameter:
Omit the first parameter (set values before the loop starts):
Using the continue statement - Loop through a block of code, but skip the value of "3":
Using the break statement - Loop through a block of code, but exit the loop when the variable i is equal to "3":
Omit the second parameter. In this example, we also use the break statement to exit the loop when i is equal to "3" (if the second parameter is omitted, you must provide a break inside the loop. Otherwise the loop will never end, and your browser will crash):
Loop through the indices of an array, in descending order (negative increment):
Omit the last parameter, and increment the values inside the loop:
Loop through the nodes of a NodeList object and change the background color of all <p> elements in the list:
An example of a nested loop (a loop inside a loop):
JavaScript Tutorial: JavaScript For Loop
JavaScript Reference: JavaScript for ... in Statement
JavaScript Reference: JavaScript break Statement
JavaScript Reference: JavaScript continue Statement
JavaScript Reference: JavaScript while Statement