Back to State Challenge
OOP Studio Ages 9-15

Object Collections

Students put many objects into an array and use a loop to make every object act.

15-20 min Ages 9-15 OOP JavaScript

Collections of objects

Put objects in an array and you get a kennel full of robot pets — one variable, many critters. Then a loop can visit every pet and ask for its status, no matter how many you adopt.

let pets = [ ... ] 🤖 🐸 🐶 [0] [1] [2] the loop visits every pet →
  1. 1

    An array of objects

    Each slot of pets holds a whole RobotPet object — name, energy, methods and all. pets[0] is Pixel; pets[1] is the next pet.

  2. 2

    Loop + method = roll call

    for each pet, call pet.status() — the loop walks the kennel and every pet announces itself. Three pets or three hundred: same three lines of code.

  3. 3

    Try it

    Adopt a fourth pet with a silly name and run the roll call again. Notice you didn't change the loop at all — that's why collections + loops run every game's enemy list.

Code Editor

Loop through objects.

Example code
class RobotPet {
  constructor(name, energy) {
    this.name = name;
    this.energy = energy;
  }

  status() {
    say(this.name + " has " + this.energy + " energy.");
  }
}

let pets = [
  new RobotPet("Pixel", 3),
  new RobotPet("Bolt", 5),
  new RobotPet("Zara", 4)
];

for (let pet of pets) {
  pet.status();
}
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.