What is the advantage of a 'getter' method on a Javascript object?

In the ‘Advanced Objects’ lesson, I just finished the exercise about getter methods.

So far, I don’t see the use of the ‘get’ keyword.

The example from this page shows:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel() {
    if (typeof this._energyLevel === "number"){
      return `My current energy level is ${this._energyLevel}`;
    } else {
      return 'System malfunction: cannot retrieve energy level'
    }
  }
};

console.log(robot.energyLevel);

But it seems to work exactly the same if I code it like this:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  energyLevel() {
    if (typeof this._energyLevel === "number"){
      console.log(`My current energy level is ${this._energyLevel}`);
    } else {
      console.log('System malfunction: cannot retrieve energy level');
    }
  }
};

robot.energyLevel();

When would I want to use the first approach when the second is more readable?

The first approach is more natural and uses the standard accessing syntax.

Ok, cool. I guess the second approach just felt more natural to me because CodeAcademy taught that approach first.

Thanks!

1 Like