Printing Instances With toString()

Priya Nair’s ten-swim card now extends Pass, and Luis Ortega’s casual pass checks in as before. Every morning, the front desk starts with a printout. The Python module prints each of the day’s passes as a line like Priya Nair (adult): ten-swim card, 3 left, and the staff read that list before the doors open.

That line comes from __str__, one of Python’s dunder methods. In this lesson, you’ll port it to JavaScript and print the desk’s list exactly the way the staff expect it.

Port str to toString()

In the Python module, Pass builds its line from the swimmer and from describe(), which each subclass overrides:

Language: Python
class Pass:
    def __init__(self, swimmer):
        self.swimmer = swimmer
        self.swims = 0

    def describe(self):
        return "casual swim"

    def __str__(self):
        swimmer = self.swimmer
        return f"{swimmer.name} ({swimmer.group}): {self.describe()}"

JavaScript’s counterpart of __str__ is a method named toString(). Here’s the module’s JavaScript file, trimmed to the parts that print. Its classes are exported, so the snippets after it can import them:

Language: JavaScript Filename: pool-passes.js
export class Swimmer {
  constructor(name, group = "adult") {
    this.name = name;
    this.group = group;
  }
}

export class Pass {
  swims = 0;

  constructor(swimmer) {
    this.swimmer = swimmer;
  }

  describe() {
    return "casual swim";
  }

  toString() {
    const { name, group } = this.swimmer;
    return `${name} (${group}): ${this.describe()}`;
  }
}

export class TenSwimCard extends Pass {
  #swimsLeft;

  constructor(swimmer, swimsLeft = 10) {
    super(swimmer);
    this.#swimsLeft = swimsLeft;
  }

  describe() {
    return `ten-swim card, ${this.#swimsLeft} left`;
  }
}

The destructuring line pulls name and group out of the swimmer, and the template literal does the job of the f-string. Now convert Priya’s card and Luis’s pass to text in two ways:

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.