Is the getter really necessary?

Learn JavaScript Syntax: Objects | Codecademy

In the exercise Team Stats is asked to create a propertie called _players and then a getter for players that returns the _players value.

  get players() {
    return this._players
  },

In the next steps is also asked to create a method addPlayer that takes the parameters of the new player and push into the getter players.

addPlayer(firstName, lastName, age) {
    let player = {
      firstName: firstName,
      lastName: lastName,
      age: age
    };
    this.players.push(player); 
  },

My question is, why push for getter players instead to _players property?
this._players.push(player);

This way, at the end of the excersise I can also log the _players property instead the getter:

console.log(team._players);

Removing the getter I can make the code cleaner, can’t I?

Getters and setters become a lot more useful once you factor in that at a professional level, coders are collaborating with other coders. Getters and setters allow someone that isn’t familiar with the codebase to still get the functionality they need to use it with their own code.

Like a lot of things in lessons, sometimes they seem overly complicated but really they are trying to set the tone for what are “best practices” and the kind of code usage you would expected in the wild.

3 Likes

The short answer - it isn’t.
The long answer - it depends. If you’re sure that each time accessing the field, you need to perform certain actions on it and return the processed result, you put this logic in the getter.

I.e. you develop a smart watch heart rate measuring software and you have a heart rate value field in your class. Instead of just giving a number - you could return its textual interpretation. In the getter you could put a logic which tells the level of danger.
100< you return “Inactive”
100-120 - “Moderate”
121-140 - “Intense”
Etc.
(I’m not a doctor - this is just an example)
In a class it is still stored as a number but when you need to get it from you field it is processed the way you need. You can think of it as a mediator logic.

Same works for setters but they are useful at the stage of assigning a value.
Hope it helped.

4 Likes