This is a review of what we covered in this tutorial on loops.

When we're writing programs, we often find that we want to repeat a bit of code over and overor repeat it but change something about it each time. To save ourselves from writing all that code, we can use a loop. JavaScript has two kinds of loops, a while loop and a for loop.

A while loop is a way to repeat code until some condition is false. For example, the while loop below will display the value of y at (30, y) as long as  y is less than 400. The loop adds 20 to y each time it runs so that y starts off at 40 but then increments to 60, 80, 100, 120, etc.

var y = 40;
while (y < 400) {
    text(y, 30, y);
    y += 20;
}

It's important that the condition inside the parenthesis becomes false at some pointotherwise we'll have what's known as an infinite loop! That's what would happen if we removed y += 20 because y would be 40 forever. Since y would always be less than 400, the program would never know when to stop.

var y = 40;
while (y < 400) {
    text(y, 30, y);
}

 

The for loop is similar to a while loop but with a more specialized syntax. Programmers invented the for loop when they realized they were always doing the same three thingscreating loop counter variables, like y above, incrementing them by some amount, and checking that they're less than a certain value. A for loop syntax has special places for each of those three actions. Below is a for loop that accomplishes the same result as the while loop above:

 

for (var y = 40; y < 400; y += 20) {
    text(y, 30, y);
}

 

Loops can also be nested. It's actually very common to nest for loops, especially in 2d drawings, because it makes it easy to draw grid-like shapes. When we nest a loop inside a loop, we're telling the program to "do this thing x many times, and for each time you do that, also do this other thing y many times." Think about drawing a gridwe'd want to tell the program to "create a column 10 times, and within each column, also create 15 cells." Here's how you can use nested for loops to achieve that result:

 

for (var col = 0; col < 10; col++) {
    for (var row = 0; row < 15; row++) {
        rect(col*20, row*20, 20, 20);
    }
}

 

When should you use a for loop versus a while loop? That's up to you. Many programmers prefer for loops because it's harder to accidentally create an infinite loop—because it's harder to forget to increment your counter variable—but sometimes a while loop might make more sense. Try them both!