The Creative Coder’s Field Guide
Everything You Need to Survive and Thrive with p5.js
Creative Coding · Week 6
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.
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.
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 x = 5; holds one number. let x = [5]; holds a list that happens to have one number in it.sizes, words, drops) or with a word like Array or List, so a reader knows it’s a collection (Week 2’s naming advice).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.
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
}
}
Run the array of colors from the review
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.
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
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.
| Write | Does | Gives back |
|---|---|---|
arr.push(value) | adds an element to the end | the new length |
arr.pop() | removes the last element | the removed element |
arr.length | counts the elements (no parentheses) | a number |
arr.splice(start, count) | removes count elements starting at start; can also insert | an array of what it removed |
arr.slice(start, end) | copies part of the array; the original is unchanged | a new array |
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() 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(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.
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.
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.
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
Run the working-with-text sketch
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 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:
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.
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 };
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.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
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);
}
Run the showIt() object literal sketch
Run the object literals sketch from the review
| Array | Object literal | |
|---|---|---|
| Brackets | [ ] square | { } curly |
| Values found by | position number: arr[0] | name: obj.x |
| Order matters? | yes | no |
| Best for | many things of the same kind | several facts about one thing |
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[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.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();.
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
| Symptom | Likely cause |
|---|---|
| the last item never shows up | loop uses i < length - 1, or starts at 1 |
an undefined appears, or a shape is missing | an 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 forever | push() in draw() with nothing removing old items |
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]
}
| Write | Does |
|---|---|
arr.length | number 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) |
| Write | Does |
|---|---|
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.length | number of characters |
s.split("") | string → array of characters |
arr.join("\n") | array → string, with a line feed between each |
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
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"].
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?
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()?
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.
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().
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.
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.