07 - Loops

JavaScript Loops

For Loop

One of the things that computers are great at are repetitions. Imagine having to create 1000 shapes on screen with varying parameters. It would take us an unreasonable amount of time to do so with our current programming knowledge. For this kind of cases where we want to repeat our code as it is or with variations we can leverage a programming structure called loops. A loop allows us to execute a block of code over and over again.

We are already familiar with the idea of a loop in p5.js. If you think about it, the draw function is a continuous loop that gets executed over and over again until we exit the p5.js program. In this chapter, we will learn how to build this kind of loops ourselves.

There are a couple of different kinds of loop structures in JavaScript, but a for loop is by far the most popular. It allows us to repeat an operation for a given amount of times. A for loop has four parts. Here is an example of how a for loop is constructed.

	for (var i = 0; i < 10; i = i + 1) {
		//do something
	}

In the first part, we initialize a variable that would keep track of the number of times that the loop gets executed - let’s call this a counter variable.

	var i = 0;

By convention, inside the for loop, we usually tend to use short variable names like i or j, especially if that variable is only in use for controlling the flow of the for loop. But feel free to use other names as well if it makes sense for your use case.

In the second part, we define a test condition for our loop which gets evaluated each time the loop is about to start. In this example, we are checking to see if our counter variable is smaller than the number 10.

	i < 10;

In the third part, we define a way to update the counter variable which gets evaluated at the end of the loop. In this example, we get the current value of the variable i and add one to it.

	i = i + 1;

Finally, inside curly braces we write the code that we want to have repeated. Once the counter variable doesn’t satisfy the test condition, the loop terminates, and the program returns to its normal evaluation.

If the test condition never fails, then we would have a loop that would end up creating an infinite loop, a loop that doesn’t have an exit condition so that it keeps going on and on until the program is terminated by external means. The draw function in p5.js is in an infinite loop; it keeps drawing to the screen until we close the browser window.

Even though infinite loops are a valid use case, loops are most commonly used for executing an operation for a known amount of times. Let’s create a loop that will draw given number of ellipses to the screen using a for loop.

Get hands-on with 1200+ tech skills courses.