Describe and Compare Plants

At the end of the last lesson, Mei’s four plants came from one Plant class, but logging one with console.log() printed a structure, Plant { name: 'Goldie', ... }, instead of the line she wanted for her morning list. She has a second wish too. When she types a plant in twice by mistake, she’d like her tracker to notice that the two entries describe the same plant.

In this lesson, you’ll give the Plant class a .toString() method that turns a plant into a sentence and an .equals() method that compares two plants by their data. You’ll also see why console.log() and === carry on as before. Start with the sentence and with what JavaScript does when you drop an object into a template literal.

Describe a Plant in Words

A template literal has to turn every value inside ${} into text, and an object has no single natural way to be written as text. You can see what JavaScript does about that in a short REPL session. Start node with no filename, and try a tiny class with only a name:

Language: JavaScript
> class Plant { constructor(name) { this.name = name; } }
undefined
> const goldie = new Plant("Goldie");
undefined
> `On the shelf: ${goldie}`
'On the shelf: [object Object]'
> goldie.toString()
'[object Object]'

The template literal asked Goldie for her text form by calling .toString() on her. That works even though the class never defined the method. A Plant instance like Goldie can already use a default .toString(), and it returns '[object Object]', which tells Mei nothing. Where that default comes from is a question for the next video.

When a class defines its own .toString(), the template literal calls that one instead. Type .exit to leave the REPL, and add a .toString() method to plant.js, after .addDay():

Language: JavaScript Filename: plant.js
export class Plant {
  constructor(name, waterEveryDays, daysSinceWatered) {
    this.name = name;
    this.waterEveryDays = waterEveryDays;
    this.daysSinceWatered = daysSinceWatered;
  }

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

  water() {
    this.daysSinceWatered = 0;
  }

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

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

The method accesses the plant’s data through this, like the others, and it returns a string. It doesn’t print anything. Whoever asked for the text decides what to do with it. Save this as describe.js to try it:

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.