Search code examples
javascriptarraysobjectget

Getter method does not need underscore to reference. Why?


I'm new to objects & methods and I'm creating a new key-value pair starting with an '_' (underscore) to see that it shouldn't be changed.

I just realized that I don't need to use the '_' when I create a getter method.

Why is that?

I am just learning about JavaScript and objects to be precise.

const team = {
  _players: [{
    firstName: 'Josh',
    lastName: 'Huan',
    age: 27
  },
  {
    firstName: 'Greg',
    lastName: 'Peterz',
    age: 33
  }
  ],
get players() {
  return this._players;
}

};

I thought that I just use the '_players' as the reference to the getter method, like 'get _players()...' but instead I don't need to use underscore.

Thank you guys in advance!


Solution

  • I don't need to use the '_' when I create a getter method.

    You don't "need" an underscore for anything. As you noted, the underscore marks properties which shouldn't be touched from outside, but that's just a convention. It's still a normal property name like any other.

    What you need for your getter to work is just two different property names - one for the getter property and one for the data property that actually stores the value. You can use any two arbitrary property names for this.