for...of in practice {Being able to treat an array as a group of related data is one of the most central ways of creating more complex and larger-scale programs. Let’s go a little further!
So we’ve seen that for...of let us draw a set of flies to the canvas pretty easily, but let’s lean into it this further to create a more dynamic program.
Let’s add another property to the flies that will let them move, we’ll call it buzziness and we’ll use it to move them around randomly (in a fly-like way).
let flies = [
{
x: 100,
y: 125,
size: 10,
// NEW
buzziness: 4
},
{
x: 160,
y: 170,
size: 14,
// NEW
buzziness: 2
},
{
x: 180,
y: 50,
size: 5,
// NEW
buzziness: 3
}
];
We can apply the exact same idea to move the flies using their buzziness by writing a moveFly() function that will take care of that:
function draw() {
background("#87ceeb");
// Go through all the flies
for (let fly of flies) {
moveFly(fly);
drawFly(fly);
}
}
/**
* Moves the fly by changing its position randomly
* according to its buzziness
*/
function moveFly(fly) {
fly.x += random(-fly.buzziness, fly.buzziness);
fly.y += random(-fly.buzziness, fly.buzziness);
}
They move! They buzz! They are flies! And we are… the lord of the flies!
The array, specifically, is letting us act on the whole group of flies each with each key idea (movement, display) that we want to include. We can think at the level of “flies” instead of each individual array element.
This program is exceptionally tidy. Crucially, the array lets us group all our flies together, no matter how many we have. And the for...of lets us go through all the flies, no matter how many there are.
Once again, try adding a new fly or two to the array. It joins its buzzing brethren seamlessly!
So, as you can see, an array along with a for...of is a very powerful duo. We can have collections of “things” in our program and act on all of them without writing it all out explicitly.
Truly, it is beautiful.