Loops
Loops let a block of code run a certain number of times:
1
2
3
4
5
6
7
|
|
Note that in loops, the variable i is not "scoped" to the loop block even though the keyword var
is used before the variable name. Scope is covered in more depth in the Scope section.
The for
loop
A for
loop is made up of four statements and has the following structure:
1
2
3
4
5
|
|
The initialisation statement is executed only once, before the loop starts. It gives you an opportunity to prepare or declare any variables.
The conditional statement is executed before each iteration, and its return value decides whether the loop is to continue. If the conditional statement evaluates to a falsy value, then the loop stops.
The iteration statement is executed at the end of each iteration and gives you an opportunity to change the state of important variables. Typically, this will involve incrementing or decrementing a counter and thus bringing the loop closer to its end.
The loopBody statement is what runs on every iteration. It can contain anything. Typically, there will be multiple statements that need to be executed, and should be wrapped in a block ( {...}).
Here's a typical for
loop:
1
2
3
4
5
6
7
8
9
10
|
|
The while
loop
A while loop is similar to an if
statement, except that its body will keep executing until the condition evaluates to false.
1
2
3
4
5
|
|
Here's a typical while
loop:
1
2
3
4
5
6
7
8
9
10
11
12
|
|
Notice that the counter is incrementing within the loop's body. It's possible to combine the conditional and incrementer, like so:
1
2
3
4
5
6
7
8
9
|
|
Notice that the counter starts at -1 and uses the prefix incrementer (++i).
The do-while
loop
This is almost exactly the same as the while
loop, except for the fact that the loop's body is executed at least once before the condition is tested.
1
2
3
4
5
|
|
Here's a do-while
loop:
1
2
3
4
5
6
7
8
|
|
These types of loops are quite rare since only few situations require a loop that blindly executes at least once. Regardless, it's good to be aware of it.
Breaking and continuing
Usually, a loop's termination will result from the conditional statement not evaluating to true, but it is possible to stop a loop in its tracks from within the loop's body with the break statement.
1
2
3
4
5
6
7
8
9
10
|
|
You may also want to continue the loop without executing more of the loop's body. This is done using the continue statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
|