Team Stats Project (Full-Stack Software Engineer Path) clarification about getters and privacy

My only question on this is about step 6

const team = { _players: [ {firstName: 'Pablo', lastName: 'Sanchez', age: 11,}, {firstName: 'Juan', lastName: 'Salvador', age: 12,}, {firstName: 'Raul', lastName: 'Guapo', age: 13,}, ], _games: [ {opponent: 'Broncos', teamPoints: 42, opponentPoints: 27,}, {opponent: 'Jaguars', teamPoints: 31, opponentPoints: 39,}, {opponent: 'Titans', teamPoints: 35, opponentPoints: 32,}, ], get players() { return this._players; }, get games() { return this._games; }, addPlayer(firstName, lastName, age) { let player = { firstName: firstName, lastName: lastName, age: age, }; this.players.push(player); }, };

why are you expected to use the push method as 'this.players.push(player)'
and not ‘this._players.push(player)’ ?
is it because we’re pushing it to the getter method?
I guess I could use some clarification as to why the _ is left out cause that was my problem last project too, so obviously I’m not understanding something

In this context I would say that it doesn’t matter whether you use ‘this.players.push(player)’ or ‘this._players.push(player)’. The instructions in the mealmaker project and this one aren’t really well fit to explain the concept of getters and setters, I think. Here, it is just redundant.

Yes, you get the _players object from the getter. You could say that you just take a d-tour through the getter.

Two reasons:

  1. You may not have a duplicate key in an object. and get _players(){} and _players: [] would be a duplicate key: _players. Whether you have the keyword ‘get’ or not.
  2. The underscore mimicks a principle known from other programming languages: privacy. Javascript doesn’t have that but programmers use it to structure their code. The underscore indicates that a property is supposed to be private and the programmer does not expect it to be altered from the outside. That’s where the getters and setters come in. They indicate that you may reach (and change) the properties and how that is supposed to happen.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.