Skip to content

A5 - The for Loop

JavaScript for loops differ quite substantially from Python for loops.

Let's start by looking at an example that will simplify what we started with in the previous assignment:

for (let x = 0; x < width; x += 50) {
    circle(x, 200, 25)
}

There are three chunks to a for loop, separated by semicolons:

  1. Initialize a variable - In our example, let x = 0
  2. State a condition for the loop to continue - In our example, x < width
  3. Specify a statement to occur after each iteration of the loop, normally to increment the variable - In our example, x += 50

To summarize the above example, we're saying: Create a variable x, and initialize it to zero. Keep looping while x < width, and increment x by 50 after each loop iteration.

Nested for Loops

Nested loops can be used to draw a grid pattern. Here is an example that draws a grid of circles. This code would go inside the draw() function.

for (let x = 0; x <= width; x += 50) {
    for (let y = 0; y <= height; y += 50) {
        circle(x, y, 25)
    }
}

Recall from our Python unit that for each iteration of the outer loop, the inner loop runs through completely. So if width and height were set such that each loop iterates ten times, we would have 100 circles in total.

We can add some conditional code inside nested loops to get some interesting patterns. For example, this is how we can draw a checkerboard:

for (let x = 0; x <= width; x += 50) {
    for (let y = 0; y <= height; y += 50) {

        if ((x + y) % 100  == 0)
            fill("black")
        else
            fill("red")

        rect(x, y, 50, 50)
    }
}

Note that the percent sign in the above example is the modulo operator.

Your Task

Run the update. Open the folder Unit 2/a5 in Visual Studio Code. Draw some patterns using for loops, including nested loops. There are a couple examples in the file to help get you started.

Just like the previous assignment, you can experiment with changing things such as colour, shape and size.