← All lessons/Objects· Lesson 29 of 32

An array of objects

Combine arrays and objects to manage a whole crowd of things at once.

About 8 min

Many objects, one list

One ball is nice. A hundred would be tedious to name. Instead, put your objects inside an array — a list written with square brackets [ ]. Each item is its own object with its own properties.

let dots = [
  { x: 100, y: 200, size: 60 },
  { x: 200, y: 120, size: 90 },
  { x: 300, y: 260, size: 40 },
];
An array holding three dot objects.

Looping over the array

A for loop walks the list one index at a time. dots[i] is the object at position i, so dots[i].x reaches into that object for its x. Draw inside the loop and every object appears:

Three dots drawn from one loop.

TIP

Add a fourth object to the dots array and run it again — the loop draws it automatically, no extra code needed. That's the power of combining arrays and objects.

Your turn

Draw three dots from an array. An array dots of three objects (each with x, y, and size) is provided. Write a for loop over dots that draws each one with ellipse(dots[i].x, dots[i].y, dots[i].size, dots[i].size).

Hints