Add Getters and Setters

Goldie’s day count is safe now because only the methods inside the Plant class can change it. That safety leaves two gaps, though. Outside code can’t even read the count to show it to Mei, and nothing stops a line such as moss.waterEveryDays = -7 from giving Moss an interval that makes no sense.

In this lesson, you’ll close both gaps with getters and setters, methods that JavaScript runs when code reads or assigns to a property. You’ll be able to predict what each read and assignment does, including the errors it can throw, and decide when a getter fits better than a method. The quicker fix is letting outside code read the count without letting that code change it, so start there.

Read Values Through Getters

Outside code needs to read Goldie’s count, but #daysSinceWatered is private. You could add a method such as .getDaysSinceWatered() and call it with parentheses. A getter reads more naturally. It’s a method with the get keyword in front of its name. Outside code reads it like any other property, with no parentheses, and JavaScript calls the method behind the scenes and hands back what it returns.

The .needsWater() method is a good candidate for a getter too. It takes no arguments, changes nothing, and answers a question about the plant’s data. As a getter, goldie.needsWater reads as a fact about Goldie, worked out at the moment you ask.

Open plant.js and replace its contents with this version. It adds a .daysSinceWatered getter and turns .needsWater() into a getter:

Language: JavaScript Filename: plant.js
export class Plant {
  wateringLog = [];
  #daysSinceWatered;

  constructor(name, waterEveryDays, daysSinceWatered) {
    this.name = name;
    this.waterEveryDays = waterEveryDays;
    this.#daysSinceWatered = daysSinceWatered;
  }

  get daysSinceWatered() {
    return this.#daysSinceWatered;
  }

  get needsWater() {
    return this.#daysSinceWatered >= this.waterEveryDays;
  }

  water() {
    this.wateringLog.push(this.#daysSinceWatered);
    this.#daysSinceWatered = 0;
  }

  addDay() {
    this.#daysSinceWatered += 1;
  }

  toString() {
    const every = this.waterEveryDays;
    return `${this.name} (water every ${every} days)`;
  }

  equals(other) {
    return (
      this.name === other.name &&
      this.waterEveryDays === other.waterEveryDays &&
      this.#daysSinceWatered === other.#daysSinceWatered
    );
  }
}

The getter .daysSinceWatered and the private field #daysSinceWatered have different names because the # is part of a private name. The field holds the value, and the getter is the public way to read it. A field that stores the value behind a getter like this is called its backing field. The .needsWater getter has no field of its own. It computes its answer from two other values every time it’s read.

Replace today.js so it reads both getters before and after Goldie is watered:

Language: JavaScript Filename: today.js
import { Plant } from "./plant.js";

const goldie = new Plant("Goldie", 5, 6);
console.log("Days since watered:", goldie.daysSinceWatered);
console.log("Needs water:", goldie.needsWater);
goldie.water();
console.log("Days since watered:", goldie.daysSinceWatered);
console.log("Needs water:", goldie.needsWater);

Run it:

Language: Shell
$ node today.js
Days since watered: 6
Needs water: true
Days since watered: 0
Needs water: false

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.