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 ...