We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Getters and Setters

In JavaScript classes, getters and setters let us define special methods for getting and setting the values of properties. They look like regular methods but are accessed like properties. Here's an example using the get keyword:

class User {
  constructor(name, age) {
    this._name = name;
    this.age = age;
  }

  get name() {
    return this._name.toUpperCase();
  }
}

const lane = new User("Lane", 30);
console.log(lane.name); // LANE

Notice that we've renamed this.name to this._name in our constructor to avoid a name collision with the getter itself.

A setter lets us control what happens when a property is changed. For example, we could validate a user's age to make sure it's not negative:

class User {
  constructor(name, age) {
    this.name = name;
    this._age = age;
  }

  get age() {
    return this._age;
  }

  set age(value) {
    if (value < 0) {
      throw new Error("Age can't be negative.");
    }
    this._age = value;
  }
}

const lane = new User("Lane", 29);
lane.age = -5; // "Age can't be negative."
console.log(lane.age); // 29

Personally... I hate this. When I get or set a value in property field, I expect that I'm dealing with a raw value, not calling a custom function! There are certain patterns that make heavy use of this feature (e.g. reactive state in certain front-end frameworks), but my advice is to only use it when you truly need it.

Assignment

Textio's Contact class currently accepts invalid phoneNumbers and doesn't format them well when displayed. Fix this by implementing getters and setters.

Tip

Strings have a .slice() method that should be useful.