JS Team Stats Underscore

Hello,

In my code below I found that I could use .players and ._players interchangeably. Any idea why? I commend below the code in my script, but included the excerpts below:

  return this.players.push(addPlayer);
  //why not? return this._players.push(addPlayer);

 console.log(team.players);
 //same here, can use ._players interchangeably
const team = {
  _players: [
    { firstName: 'Pete',
      lastName: 'Wheeler',
      age: 54
    }, {    
      firstName: 'Pablo',
      lastName: 'Sanchez',
      age: 11
    }, {
      firstName: 'Duder',
      lastName: 'Myway',
      age: 28
    }, ],
  
   _games: [
    { opponent: 'Broncos',
      teamPoints: 42,
      opponentPoints: 27
    }, {
      opponent: 'Packers',
      teamPoints: 10,
      opponentPoints: 38
    }, {
      opponent: 'Seahawks',
      teamPoints: 20,
      opponentPoints: 21
    }, ],

  get players() {
    return this._players;
  },
  get games() {
    return this._games;
  },
  
  addPlayer(firstName, lastName, age) {
    let addPlayer = {
      firstName: firstName,
      lastName: lastName,
      age: age,
    };
    return this.players.push(addPlayer);
      //why not? return this._players.push(addPlayer);
    },
  
  addGame(opponentName, teamPoints, opponentPoints) {
    let addGame = {
      opponent: opponentName,
      teamPoints: teamPoints,
      opponentPoints: opponentPoints,
    };
    return this.games.push(addGame);
  },

};

team.addPlayer('Steph', 'Curry', 28);
team.addPlayer('Lisa', 'Leslie', 44);
team.addPlayer('Bugs', 'Bunny', 76);

team.addGame('Falcons', 39, 10);

console.log(team.players);
//same here, can use ._players interchangeably
console.log(team.games);

link for team stats project:
https://www.codecademy.com/paths/back-end-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-objects/projects/team-stats

That’s the power of your getter. This code is what allows that to happen:

Since you’re returning the this._players array in your getter named players, you can access it using this.players or team.players

The exercise that went over getters in your career path here demonstrated it by combining a first name and last name, but by returning an array, methods like .push() can still be called too.

2 Likes

If I am understanding correctly, because of the getter function one can use this.players or this._players for the first situation and team.players or team._players for the second situation.

Please correct me if my understanding is wrong.

Thank you!

1 Like