Arrays


Arrays


July 18, 2020

tutorial p5.js javascript arrays

Now you know how to create variables and functions, and you know how to use for loops to repeat a block of code.

So far, the variables you’ve seen have held a single value. This tutorial introduces arrays, which hold multiple values.

Multiple Variables

Let’s start with an example sketch:

This sketch uses a circleY variable to show a circle falling down the screen. Incrementing the circleY each frame causes it to fall. The if statement detects when the circle reaches the bottom, and resets the circle back to the top of the screen.

falling circle

The Bad Way

What if you want to add another circle? You might be tempted to use another variable:

This code uses two variables: circleYOne and circleYTwo to show two circles that fall from the top of the screen.

two falling circles

Creating an Array

What if you wanted to add a third circle? Or ten more circles? You could keep adding variables, but that’s going to make your program very long and hard to work with. Instead, you can use an array.

An array is a single variable that holds multiple values. Remember that to create a variable you use the let keyword to give it a name and a value. Creating an array is similar:

  • Use the let keyword. You can also use the const keyword, but to keep it simple I’m going to stick with let.
  • Give it a name.
  • Give it an array value. An array value is multiple values inside square brackets [] and separated by commas.

For example, this line of code creates an array named circleY that holds two values, 10 and 20:

let circleY = [10, 20];

Accessing an Array

An array is a variable that holds multiple values. To use an individual value inside an array, you can use the array access operator. The array access operator is a number value inside square brackets []. That number provides the index of the array value that you want to use. For example, this line of code accesses the first and second values from the array to draw two circles:

circle(100, circleY[0], 25);
circle(200, circleY[1], 25);

This line of code does the same thing as before, but now it’s getting the values from an array instead of two separate variables.

Start at Zero

You might notice that the code uses 0 instead of 1 to get the first value from the array. That’s because array indexes start at zero!

The second value from the array has 1 as an index:

// draw the second circle
circle(200, circleY[1], 25);

This can be pretty confusing, but remember that array indexes start at zero. So if you have an array with ten values, the last index is 9.

Setting an Array Index

Just like you can modify the value a variable holds, you can modify the value an array index holds.

This line of code reassigns the first index of the array to a new value:

circleY[0] = 42;

And this line of code adds 5 to the first array index:

circleY[0] = circleY[0] + 5;

Which can be shortened to:

circleY[0] += 5;

The Bad Way with Arrays

Putting it all together, you could rewrite the sketch to use arrays instead of single-value variables:

I’m using this example to show how arrays work, but you wouldn’t actually write code like this. If you added a third value to the circleY array, you’d still need to add the code that uses that new value. That’s going to get very annoying! Instead of copying the same line of code over and over again, you can use for loops to make your life easier.

For Loops

Let’s say the circleY array holds five values. You can write code that draws five circles:

circle(50, circleY[0], 25);
circle(100, circleY[1], 25);
circle(150, circleY[2], 25);
circle(200, circleY[3], 25);
circle(250, circleY[4], 25);

(I’m leaving out the code for moving and resetting the circles, but imagine how long that code would be!)

This will work, but notice that this code contains a pattern: it uses an index that starts at 0, increases by 1, and stops at 4.

That means you can rewrite this code to use a for loop instead!

for (let i = 0; i < 5; i++) {
  circle(50 * (i+1), circleY[i], 25);
}

This code uses a for loop with a loop variable i that goes from 0 to 4. When the i variable reaches 5, then i < 5 evaluates to false and the loop exits.

Inside the body of the loop, the code uses that loop variable to access every index of the array. It also uses that loop variable to calculate the x value of each circle.

You can rewrite the code to use a for loop:

five falling circles

And that’s the cool thing about arrays, especially when you use for loops with them: you now have 5 falling circles, without any extra code! You only have to write the code that draws, moves, and resets a circle once, and then you can apply that code to every circle in the array.

Array Length

When you’re using a for loop with an array, you have to know how many values are in the array, so you know which index to stop at.

When there are two values, the for loop looks like this:

for (let i = 0; i < 2; i++) {

And when there are ten values, the for loop looks like this:

for (let i = 0; i < 10; i++) {

In other words, you always want to stop the loop when its loop variable equals the number of elements in the array, which is also called the length of the array. If you try to access an index that’s larger than the length, you’ll get an error!

So if you add a variable to the array initialization (the values in the square brackets []), you’ll have to change the check in the for loop. Wouldn’t it be nice if the computer could keep track of that for you?

You guessed it: the computer does keep track of the length of an array! To use the length value, you type .length after the name of an array:

let numberOfValues = circleY.length;

You can use this length variable exactly like you can any other variable, including in a for loop check:

for (let i = 0; i < circleY.length; i++) {

Now if you add values to the array, you no longer have to modify the for loop check yourself. The length variable will always contain the length of the array, so the for loop will work no matter how many elements the array contains.

Delayed Initialization

Remember that declaring a variable means creating in by giving it a name, and initializing a variable means giving it a starting value. Reassigning a variable means changing its value.

So far, the code above has initialized arrays as soon as it declares them, using values inside square brackets []:

let circleY = [50, 100, 150, 200, 250];

But what if you don’t know what the values should be yet? In this case, you can delay the initialization of the array.

To create an array without initializing its values, you can use empty square brackets [].

This line of code creates an empty array:

let circleY = [];

Now you can set the value of each of the indexes individually:

  circleY[0] = 50;
  circleY[1] = 100;
  circleY[2] = 150;
  circleY[3] = 200;
  circleY[4] = 250;

Or better yet, you can use a for loop:

for (let i = 0; i < circleY.length; i++) {
  circleY[i] = (i + 1) * 50;
} 

The Payoff

Putting all of this together, here’s an example that shows 25 falling circles:

25 falling circles

Imagine how much code this would take if it wasn’t using arrays and for loops!

Challenge: Change this code to show 100 falling circles, all falling at different speeds!

Summary

Arrays are variables that hold multiple values. By combining them with for loops, you can write programs that handle a lot of data in just a few lines of code.

Homework

  • Create a sketch that shows rain drops or snow flakes falling.
  • Create a sketch that shows a trail of circles that follow the mouse. Hint:. store the previous 25 positions of the mouse in an array and draw those to the screen!

Arrays Examples

Comments

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!