Skip to main content

Arrays

Arrays

Difficulty : Beginner-Intermediate

This tutorial assumes you have a basic understanding of coding in Processing or p5, and are comfortable using variables, if statements and for loops.

The What and the Why

In order to understand why So far we've learnt that we can use variables to name data in our code, as so:

  var myVariable = 200;
  
  console.log(myVariable);

p5 Edditor

And we know that we can use these variable in our sketch. In the following example I create variables X and Y, and use them to as the x and y coordinates in an ellipse function

var x = 100;
var y = 100;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  ellipse(x, y, 20,20);
}

p5 Editor

arraysTutorial_IMG001.png

Now what if we wanted to have a lot of circles, like in the image below?

arraysTutorial_IMG002.png

You might be thinking of doing something like this, with seperate variables for every ellipse:

var x1 = 20;
var y1 = 100;
var x2 = 213;
var y2 = 209;
var x3 = 100;
var y3 = 100;
var x4 = 100;
var y4 = 100;

And you'd be right! This is a perfectly valid approach. However, imagine if we had hundreds of circles, we'd need hundreds of variables as well. Things would start getting messy quickly and we'd have to make sure we were keeping track of everything individually. Going further, say we wanted to manipulate all of our circles in a similar way (for example, move them all left) we would end up with lots and lots of lines of really similar code. Wouldn't it be good if we could handle all this data at once?

Well... WE CAN! This is what arrays are perfect for. An erray is essentially just like other variables, only instead of storing one piece of information they store many.