Back to Object Challenge
OOP Studio Ages 9-15

Methods Change State

Students learn that methods can change an object's internal values, like energy, score, or health.

15-20 min Ages 9-15 OOP JavaScript

Methods change state

An object remembers its own facts — that memory is called state. A method is an action that can change that state: every time the robot pet plays, its energy battery drains by one.

🤖 play() energy: 2
  1. 1

    State = the object's memory

    this.energy = 3 in the constructor gives every new pet a full battery. That number lives inside the object and sticks around between actions.

  2. 2

    Methods update it: this.energy = this.energy - 1

    Each play() call reads the pet's own energy, subtracts one, and saves it back. Call it three times and the battery hits zero — the object remembered every play.

  3. 3

    Try it

    Add a recharge() method that sets this.energy = 3 again, then play, recharge, and play some more. You're managing state — the heart of every game.

Code Editor

Change a property with a method.

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

  play() {
    this.energy = this.energy - 1;
    say(this.name + " played. Energy: " + this.energy);
  }
}

let pixel = new RobotPet("Pixel");
pixel.play();
pixel.play();
Output

Program result

Robot ready to speak your strings

Type real JavaScript, then run it.