The Creative Coder’s Field Guide

Everything You Need to Survive and Thrive with p5.js

Creative Coding · Week 6

Line-UpArrays, strings and object literals in p5.js

One variable, one value has carried you a long way. But a sketch with fifty raindrops shouldn’t need fifty variables. This week you learn the array, a single variable that holds a numbered list of values, and the object literal, a single variable that holds a bundle of named values. Put them together and a loop can manage a whole crowd.

Arrays + strings + object literals · editor.p5js.org · Understand → Know → Do
01The idea

Many values, one name

Last week’s robot grid needed color1 and color2. A third color means color3. A truck sketch with three trucks needs x1, y1, x2, y2, x3, y3, and every new truck, color or speed adds more. It gets messy fast.

An array fixes this by holding many values under one name, in order. Instead of five color variables you have one variable, myColors, holding all five. Instead of saying which variable, you say which position: item 0, item 1, item 2.

That position is a number, and you already know how to produce a run of numbers: a for loop (Week 4). Arrays and loops are made for each other. A loop counts through the positions, and each time around it works with one item from the list.

Arrays are everywhere. A playlist, a deck of cards, the letters in a word, the pixels on your screen: all of these are naturally lists of things in order. Once you can store a list, you can draw, move and change every item in it with a few lines of code.

02Syntax

Square brackets make a list

You create an array with square brackets. Put the values inside, separated by commas. Each value is called an element.

let myColors = ["#4e4187", "#30c5ff", "#f9e0d9", "#b26e63", "#cec075"];
let sizes = [10, 25, 40];
let words = ["Hello", "Code", "!"];
let myArray = [];      // an empty array, ready to fill later
let myColors = [ … ]; "#4e4187" "#30c5ff" "#f9e0d9" "#b26e63" "#cec075" 0 1 2 3 4 index myColors.length is 5 · the last index is 4
Elements are kept in order, and the positions are numbered starting at 0, not 1. The position number is called the index.
  • Any values can go in an array: numbers, strings, booleans, colors, even other arrays or objects (section 08).
  • The brackets are the whole difference. let x = 5; holds one number. let x = [5]; holds a list that happens to have one number in it.
  • Name arrays in the plural (sizes, words, drops) or with a word like Array or List, so a reader knows it’s a collection (Week 2’s naming advice).
03Indexes

Reading and changing one element

To use one element, write the array’s name, then the index in square brackets. myColors[0] is read aloud as “myColors at index zero”, or “myColors sub zero”. It works anywhere a plain value would.

let sizes = [10, 25, 40];

circle(100, 200, sizes[0]);   // a 10-pixel circle
circle(200, 200, sizes[2]);   // a 40-pixel circle
fill(myColors[1]);            // the light blue

sizes[1] = 99;                // change one element: now [10, 99, 40]
sizes[0] += 5;                // update operators work too: now [15, 99, 40]
print(sizes.length);          // 3: how many elements

The index can be any expression that works out to a whole number (Week 2), including a variable. That’s the key to the next section: sizes[i] means “whichever element i points at right now.”

The off-by-one trap. Because counting starts at 0, the last element of an array is at length - 1, not at length. In a three-element array, sizes[3] doesn’t exist. JavaScript won’t stop with an error; it quietly gives you undefined, and a shape drawn with undefined simply doesn’t appear. If your last item is missing or something vanishes, check your indexes first.

04Loops

A loop visits every element

Here’s the pattern you’ll write more than any other this semester. Start the counter at 0, keep going while it’s less than the array’s length, and use the counter as the index:

let myColors = ["#4e4187", "#30c5ff", "#f9e0d9", "#b26e63", "#cec075"];

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

function draw() {
  background(220);
  for (let i = 0; i < myColors.length; i++) {
    fill(myColors[i]);
    rect(i * 80, 0, 80, height);    // one stripe per color
  }
}

Read the loop header carefully, because every part of it matters:

  • let i = 0 because the first index is 0.
  • i < myColors.length, with < and not <=, so the loop stops after the last real index (4) and never asks for index 5.
  • myColors.length instead of the number 5, so you can add a sixth color to the list and the loop keeps up on its own.

The counter i does two jobs here: it picks the color with myColors[i] and it places the stripe with i * 80. That’s the pattern-and-formula idea from Week 4, with the array supplying the values.

Know about: random() can pick from a list

Hand p5’s random() an array instead of two numbers and it returns one element, chosen at random. It’s the easiest way to pick from a palette:

fill(random(myColors));     // any one of the five colors
05Changing arrays

Adding, removing, and slicing

Arrays don’t have a fixed size. They come with built-in functions for growing and shrinking them. A function that belongs to a value like this is written after a dot, as in myArray.push(10); you’ll learn exactly why next week.

WriteDoesGives back
arr.push(value)adds an element to the endthe new length
arr.pop()removes the last elementthe removed element
arr.lengthcounts the elements (no parentheses)a number
arr.splice(start, count)removes count elements starting at start; can also insertan array of what it removed
arr.slice(start, end)copies part of the array; the original is unchangeda new array
push("D") pop() splice(1, 1) ABC ABCD ABCD ABC ABCD ACD added at the end last one removed index 1 removed; rest slide left 0 1 2 3
After a splice(), every element after the gap gets a new index: C was at 2 and is now at 1. Keep that in mind if you’re removing elements inside a loop.

splice() can remove, insert, or replace

splice() changes the contents of an array in place. Its full form is splice(start, deleteCount, item1, item2, …): go to index start, remove deleteCount elements, then insert any items you listed.

let months = ["Jan", "March", "April", "June"];

months.splice(1, 0, "Feb");     // at index 1, remove 0, insert "Feb"
print(months);                  // ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, "May");     // at index 4, remove 1, insert "May"
print(months);                  // ["Jan", "Feb", "March", "April", "May"]

months.splice(0, 1);            // remove 1 element at index 0
print(months);                  // ["Feb", "March", "April", "May"]

The MDN splice reference has every variation.

slice() copies without changing

slice(start, end) copies the elements from start up to but not including end, into a brand-new array. A negative index counts back from the end.

let animals = ["ant", "bison", "camel", "duck", "elephant"];

print(animals.slice(2));       // ["camel", "duck", "elephant"]
print(animals.slice(2, 4));    // ["camel", "duck"]
print(animals.slice(1, 5));    // ["bison", "camel", "duck", "elephant"]
print(animals.slice(-2));      // ["duck", "elephant"]
print(animals.slice(2, -1));   // ["camel", "duck"]
print(animals.slice());        // a copy of the whole array

See the MDN slice reference for more. The names are easy to mix up: splice pulls elements out of the original; slice leaves it alone.

Growing an array while the sketch runs

Because push() works anywhere, an array can start empty and fill up as the sketch runs. This sketch remembers where the mouse has been, keeps only the most recent 40 positions, and draws them all:

let trailX = [];
let trailY = [];

function draw() {
  background(220);
  trailX.push(mouseX);
  trailY.push(mouseY);

  if (trailX.length > 40) {    // too long? drop the oldest
    trailX.splice(0, 1);
    trailY.splice(0, 1);
  }

  for (let i = 0; i < trailX.length; i++) {
    circle(trailX[i], trailY[i], i);   // newer = bigger
  }
}

Two arrays that have to stay in step is a little awkward. Section 08 shows a neater way.

06Strings & text

Text is a list of characters

You’ve worked with numbers and booleans. The third everyday data type is the string, which holds character data: letters, digits, spaces and punctuation, written inside quotes.

Putting text on the canvas

text(string, x, y) draws a string at a position. A handful of other functions style it, the same way fill() styles shapes:

fill(200, 0, 0);

textFont("Courier");   // also try "Georgia", "Helvetica", "Verdana",
                       //   "Arial", "Times", "Comic Sans MS"
textStyle(NORMAL);     // or ITALIC, BOLD, BOLDITALIC
textSize(50);

text("Dave Was Here", 100, 40);

let myString = "Hello World";
text(myString, 200, 100);   // strings live happily in variables

Two strings joined with + make a longer string, and a number joined to a string becomes part of the text: text("Score: " + score, 20, 30). That’s the string flavor of expressions that Week 2 promised.

A string behaves a lot like an array

A string is an ordered list of characters, so a few array ideas carry straight over. myString.length counts its characters, and myString[0] is its first character, "H".

Strings also have a special character for formatting: "\n", the line feed, which makes whatever follows start on the next line. Put one between every letter and the word stands up vertically, with each letter still upright:

text("H\ne\nl\nl\no", 200, 200);   // draws H, e, l, l, o down the canvas

Typing all those \ns by hand is tedious. Instead, convert the string to an array, then build it back into a string with \n in between:

string "Hello" .split("") array Hello .join("\n") drawn with text() Hello split("") cuts between every character. join("\n") glues them back with a line feed between each one.
The character you pass to join() is called a delimiter because it separates the pieces. join(", ") would give "H, e, l, l, o".
let myStr = "Hello World";
print(myStr);                 // Hello World

let myArray = myStr.split("");
print(myArray);               // ["H","e","l","l","o"," ","W","o","r","l","d"]

let myNewStr = myArray.join("\n");
text(myNewStr, 200, 50);      // Hello World, top to bottom

// or all in one step:
text(myStr.split("").join("\n"), 200, 50);

Why not just rotate it? rotate() from Week 5 can turn a word 90°, but then every letter lies on its side too. Splitting and joining keeps each letter upright and stacks them, the look you see in the “digital rain” of the Matrix films. You’ll build exactly that next week.

07Object literals

Object literals: one name, many labeled values

An array keeps values in order and finds them by number. Sometimes you want to keep values together by meaning instead: a point’s x and its y, or a message’s text and where to draw it. For that, JavaScript has the object literal: curly braces holding named values.

let dObj = { x: 100, y: 200 };
curly braces hold the whole bundle let myText1 = { x: 60, y: 200, aText: "Hello There" }; one property key value key: value pairs, separated by commas
Each key: value pair is a property. The key is a name you choose, like a variable name; the value can be anything a variable could hold.

Dot notation

To reach a property, write the object’s name, a dot, and the key. Read myText1.x as “myText1’s x”. It works for reading and for changing:

let myText1 = { x: 60, y: 200, aText: "Hello There" };
let myText2 = { x: 10, y: 300, aText: "ANOTHER Message" };

text(myText1.aText, myText1.x, myText1.y);   // read three properties
myText2.y = 350;                             // change one
myText2.y += 1;                              // update operators work too

Objects make great arguments

Pass an object to a function (Week 5) and the function gets all its properties in one argument. From the review, a showIt() function that draws any message object, called once for each:

function draw() {
  background(220);
  showIt(myText1);
  showIt(myText2);
}

function showIt(obj) {
  textSize(24);
  text(obj.aText, obj.x, obj.y);
}
 ArrayObject literal
Brackets[ ] square{ } curly
Values found byposition number: arr[0]name: obj.x
Order matters?yesno
Best formany things of the same kindseveral facts about one thing
08Arrays of objects

A list of bundles

Arrays and objects combine naturally. An array of object literals is a list of things, where each thing carries its own labeled facts. This is how most real programs store their data: a list of songs, each with a title and length; a list of particles, each with a position and speed.

dots x: 40y: 120size: 12 x: 310y: 75size: 30 x: 200y: 300size: 8 0 1 2 dots[1].x → 310: index 1, then its x
Read dots[1].x left to right: start at dots, step into the element at index 1, then take that object’s x. Inside a loop it becomes dots[i].x.

Fill the list in setup(), use it in draw()

A loop in setup() builds the objects and pushes each one into the array. A loop in draw() visits each object, moves it, and draws it. This sketch makes 100 dots that drift down the canvas:

sketch.js

let dots = [];

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 100; i++) {
    dots.push({
      x: random(width),
      y: random(height),
      size: random(4, 16),
      speed: random(0.5, 3)
    });
  }
}

function draw() {
  background(220);
  for (let i = 0; i < dots.length; i++) {
    moveDot(dots[i]);
    drawDot(dots[i]);
  }
}

function moveDot(d) {
  d.y += d.speed;
  if (d.y > height) {    // off the bottom? start again at the top
    d.y = 0;
  }
}

function drawDot(d) {
  circle(d.x, d.y, d.size);
}

Notice what moveDot() does: it changes d.y, and the change sticks. When you pass an object to a function, the function gets the same object, not a copy, so updating its properties updates the one in the array. (Plain numbers don’t work that way: a function that changes a number parameter only changes its own local copy.)

Compare this with the mouse trail in section 05. One array of { x, y } objects replaces two arrays that had to stay in step.

Look at the shape of this code. Each dot is a bundle of data, and there are two functions, moveDot() and drawDot(), that only make sense for dots. Next week you’ll learn the class, which packs the data and the functions that belong with it into one definition. Then the loop in draw() shrinks to dots[i].drawIt();.

09Debug

Seeing inside an array

print() (Week 2) works on arrays and objects. In the p5 editor’s console you’ll see the whole list, and you can expand objects to look at their properties. Print in setup(), not draw(), or a 100-element array will flood the console sixty times a second.

print(myColors);          // the whole list
print(myColors.length);   // how many
print(dots[0]);           // the first object and its properties

The usual suspects

SymptomLikely cause
the last item never shows uploop uses i < length - 1, or starts at 1
an undefined appears, or a shape is missingan index past the end: arr[arr.length], or <= in the loop
“Cannot read properties of undefined”dots[i].x where dots[i] doesn’t exist
“length is not a function”arr.length(); it’s a property, no parentheses
“push is not a function”the variable was never set to []
array keeps growing foreverpush() in draw() with nothing removing old items
10Reference

Quick reference

Arrays

let arr = [];                    // empty
let arr = [10, 20, 30];          // with values
arr[0]                           // first element (10)
arr[arr.length - 1]              // last element (30)
arr[1] = 99;                     // change an element

for (let i = 0; i < arr.length; i++) {
  // use arr[i]
}
WriteDoes
arr.lengthnumber of elements
arr.push(v)add v to the end
arr.pop()remove (and return) the last element
arr.splice(i, n)remove n elements starting at index i
arr.splice(i, 0, v)insert v at index i
arr.slice(a, b)copy from a up to, not including, b
random(arr)one random element (p5)

Strings and text

WriteDoes
text(s, x, y)draw string s at (x, y)
textSize(n)text height in pixels
textFont("Georgia")typeface
textStyle(BOLD)NORMAL, ITALIC, BOLD, BOLDITALIC
"a" + "b"join strings: "ab"
s.lengthnumber of characters
s.split("")string → array of characters
arr.join("\n")array → string, with a line feed between each

Object literals

let obj = { x: 100, y: 200, label: "hi" };
obj.x            // read a property
obj.y = 50;      // change a property
arr[i].x         // property of the object at index i
11Practice

Be able to do

Predict the index

Write down what each line prints before you run it (sections 03 and 05):

let fruit = ["apple", "banana", "cherry", "date"];
print(fruit[1]);
print(fruit.length);
print(fruit[fruit.length - 1]);
print(fruit[4]);
fruit.push("elderberry");
fruit.splice(0, 2);
print(fruit);

banana, 4, date, undefined, then ["cherry", "date", "elderberry"].

Your palette

Make an array of five colors you like. Use one for loop to draw five squares in a row, each filled with the matching color from the array (section 04). Then add a sixth color to the array without changing the loop. Does a sixth square appear? Why?

A random grid

Use nested loops (Week 4) to fill the canvas with a grid of circles, filling each one with random(yourColors). Move the drawing into setup() so the colors don’t flicker every frame. What changes if you put it back in draw()?

Stand your name up

Store your name in a variable. Use split("") and join("\n") to draw it vertically (section 06). Then draw it three more times across the canvas, each in a different textFont(), using an array of font names and a loop.

Describe yourself as an object

Make an object literal with at least four properties about a shape on your canvas, for example { x: 200, y: 200, size: 80, label: "me" } (section 07). Write a function showShape(obj) that draws a circle and its label from the object’s properties. Make the circle follow the mouse by updating obj.x and obj.y in draw().

A better mouse trail

Rewrite the trail from section 05 with a single array: each frame, push({ x: mouseX, y: mouseY }), keep only the last 40 with splice(0, 1), and draw every point with trail[i].x and trail[i].y.

Confetti

Build on the falling dots in section 08. Give each object a color property picked with random() from your palette and an x speed as well as a y speed. Then add new confetti with push() whenever the mouse is pressed. Print dots.length once a second (every 60 frames) to watch the count grow.