The for loop

for loops are a powerful looping mechanism. The syntax of a for loop is:

    # Code to execute.

As you can see, there are three for loop parameters. All of which are optional.

The first parameter is evaluated once, at the beginning of the loop. Typically this is used to set the value of an existing variable or declare a new variable and assign a value to it. Often this is the counter for the loop.

The second parameter is evaluated at the beginning of each iteration of the loop. If it’s truthy then the body of the loop is executed. If it’s falsey then the loop exits.

Finally, the third parameter is evalulated at the end of each iteration of the loop.

# Print the first 10 numbers.
for (var i = 1; i <= 10; i += 1) {

# As above but notice that we use an existing variable as our counter.
var j = 1
for (; j <= 10; j += 1) {

An infinite loop can be created by omitting the test expression. We can also omit the initial expression and the iteration expression if we like. Note how the semicolons are still required after then absent first and second parameters:

for (;;) {
    print("Wakanda forever") # Prints this forever.

Of course the above infinite loop could just as easily be created with a more readable while loop:

while True {
    print("Wakanda forever")

As with while loops, we can exit them at any point with the break statement.

for (var i = 0; ; i += 1) {
    print("Wakanda forever")
    break if i == 10