Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial66 The for
Statement
MDN: Loops and Iteration: for statement
The for
statement is the most commonly used. It executes
a block of code until a condition is false. The for statement has the
following syntax:
for ( <initialize>; <condition>; <increment> ) {
// code block to do something
}
In the above example:
Line 1: The statement is declared with
for
and there are three statements which affect the loop:Initialize
executes once at the beginning of the loop. This initializes a variable which works within the loop to help manage code execution and is used to test whether the loop’s condition is still true.Condition
is the statement which needs to be true for the loop to continue running. Once the condition is false, the loop immediately stops and the script moves on to any subsequent code.Increment
updates the loop’s variable and is executed after the code block within the loop has been executed.
Line 2: This contains the code (of any length) to be executed within the loop. A
break
statement may also be added to stop the loop early, just like in theswitch
statement.