0

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!

  • 1
    Underscores are just like any other character; they don't mean anything special. What is your question? – SLaks Feb 03 '19 at 16:59
  • I thought that when I create a getter method I need to reference with the name of the key (_players). But as you can see I am not using the same name just simply 'players' without the underscore. Question is: Why don't I need it there? –  Feb 03 '19 at 17:02
  • 1
    you are basically creating a brand new method, it doesn't have any idea that `_players` even exists. You could just as well do `get monkey() { return this._players }` if you wanted and it would work just the same. – Get Off My Lawn Feb 03 '19 at 17:08
  • Thank you Get Off My Lawn. All clear now ! :) –  Feb 03 '19 at 17:16

1 Answers1

2

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.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • Thank you very much Bergi! I've mistaken it for being a reference but now it's all clear. :) –  Feb 03 '19 at 17:15