JavaScript: Working With Loops

Overview and Objectives

This lesson introduces loops, a core programming concept.

Lesson Objectives:

  • Demonstrate an understanding of the purpose of loops by integrating a For Loop into a p5 sketch.

Looping and Iterating

Looping is another commonly used control flow technique. There are several types of loops and iterators in JavaScript, but this section is about one of the most common: the For Loop.

Understanding the structure and purpose of the For Loop is important because it is a concept that is used in other languages as well.

Let’s first consider an example from a p5 sketch, and then break down the code.

Note: The code example is entirely in the setup() function so that it’s only called once — this will help clearly identify what the for loop is producing.

function setup() { createCanvas(400, 400); background(0); noStroke(); fill(255, 0, 100); for (let step = 0; step < 3; step += 1) { console.log(`drawing item ${step}`); ellipse(100*step, 100*step, 50, 50); } } function draw() { }
Code language: JavaScript (javascript)

Code Analysis:

For Loops can be broken down into the following structure:

for (initial value; value to test; update to value) { // code to run each loop cycle }
Code language: JavaScript (javascript)

Let’s first back at our initial example. Note that each of the expressions is separated by a semi-colon. You’ll get an error if you forget the semi-colon!

let step = 0 is the initial value. This variable can be whatever you like. However, the above example uses the variable step for readability. This first expression is the starting point of the loop. For this, the step counter begins at 0.

step < 3 is the limit of each loop. This value is tested each cycle through, and if it is still true, the loop continues until this evaluates as false. In this case, the loop will continue until the steps variable is no longer less than 3. As soon as this test returns false, the loop stops.

step += 1 is the iterator or update value of the loop. The += is shorthand for step = step + 1

This determines how the step variable increments with each pass through the loop. Each time through the loop, this adds 1 to the step’s value. The relationship between this value and the limit value determines the frequency and maximum times that your loop runs.

Run the example code in the editor and notice what happens. Check out both the console.log() output and the ellipses that are drawn. Note how the step variable is being used to modify the position of the ellipse!

Loops in p5

P5 is interesting in that everything inside the draw() function loops at a rate of 60 frames per second. However, you can still include loops inside this main loop! Loops are commonly used in p5 to generate interesting sketches. In order to illustrate the benefit of loops, let’s look at some code samples without and with loops.

Drawing Lines Across Canvas

A common first example for the benefit of looping is with creating a series of vertical lines drawn across the canvas. This is a great way to illustrate why and how to use a loop.

First, let’s break down the process for drawing this:

  • Create the canvas and set the background color
  • Inside draw(), make a series of lines that are 10 pixels apart
  • Write the code to place each line 10 pixels apart and repeat this until lines are drawn across the entire canvas width

Example Without a Loop:

The last part requires a high degree of repetition. The first code snippet shows how you would need to approach this without using a loop:

function setup() { createCanvas(400,400); } function draw() { background(50); // lines use stroke instead of fill for color stroke(color(80,170,100)); // draw a vertical line with line(x1, y1, x2, y2) line(10, 0, 10, height); stroke(color(80,175, 100)); line(20, 0, 20, height); stroke(color(90,180,110)); line(30, 0, 30, height); stroke(color(100,190,120)); line(40, 0, 40, height); stroke(color(110, 200 ,130)); }
Code language: JavaScript (javascript)

This code illustrates this process for only four lines! It’s already extremely repetitive and it’s not anywhere near the length of the canvas. Let’s see how this could be improved with a loop.

Example With a Loop:

Let’s refactor (rewrite with intention of improving or streamlining) our code with a For Loop. The first step is to find a part of our code that repeats.

Looking at the example, there are two parts that are repeating with a steady increment: the x1 value and the x2 value. The y1 and y2 values remain the same throughout the entire process since the lines are being drawn from the top of the canvas (y = 0) to the bottom (y = height).

The only values that are changing are the x values for each line since the line is shifting horizontally across the canvas.

function setup() { createCanvas(400,400); } function draw() { background(50); for (let xPosition = 10; xPosition < width; xPosition += 10) { // set the stroke color for the lines stroke(color(255,0,100)); // since the xPosition increments by 10, the x values in each line can be replaced by xPosition line(xPosition, 0, xPosition, height); } }
Code language: JavaScript (javascript)

The code is now much more efficient! Let’s break down the code.

In the previous sketch, the line was spaced 10 pixels apart. Remember that the syntax for line(x1, y1, x2, y2);  The loop draws vertical lines from the top to the bottom of the canvas and then moves the lines across the page, so the x1 and x2 were 10 pixels apart so
this is set as the value for the iterator.

You can use whatever variable name you like for the iterator. In this example, it makes sense to name it something that represents what it’s doing.

This is where the first line will begin, at x = 10 on the canvas. The loop will continue as long as xPosition < width.

Since the goal is to draw the vertical lines all the way across the canvas, the loop will only end once reaching the canvas width.

The increment xPosition += 10, adds 10 to the value of xPosition each time. Experiment with changing this value and see what happens!

Activity: Make Some Loops!

Let’s test your looping skills! The above example drew a grid of vertical lines spanning the width of the canvas. Your goal is to write a loop that draws a series of horizontal lines (or ellipses!) across the canvas. Experimenting with these values can come up with some very interesting sketches!

Bonus Challenge: If you’re up for a challenge, you can nest loops together. This means having a loop inside of another loop! Think about how you would need to structure this.

The best way to refine this skill is to practice. Have fun drawing some fun interactions.