Team Stats console display and Getter question

I’m not sure if this was the intended result, but when I log this project to console, I get lines that look like this:
[ { firstName: ‘Bilblo’, lastName: ‘Baggies’, age: 41 },
How do I make this more presentable?

Also, a question about getters:
I have an object _players and _games.
When I use “get”, the code does not work unless I remove the underscore.
i.e.
get _players
returns “RangeError: Maximum call stack size exceeded”
Why is that?

Thanks.

const team = {
  _players: [
    {  
    firstName: 'Bilblo',
    lastName: 'Baggies',
    age: 41
    },
    {
    firstName: 'Puu',
    lastName: 'Daboop',
    age: 39
    },
    {
    firstName: 'Shoop',
    lastName: 'Fehs',
    age: 32
    }
  ],
  _games: [
    {
    opponent: 'Plonkos',
    teamPoints: 69,
    opponentPoints: 25
    },
    {
    opponent: 'Beyderz',
    teamPoints: 55,
    opponentPoints: 22
    },
    {
    opponent: 'Dackers',
    teamPoints: 29,
    opponentPoints: 93
    }
  ],
  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);
  },
  addGame(oppName, teamPoints, oppPoints){
    const game = {
      opponent: oppName,
      teamPoints: teamPoints,
      oppPoints: oppPoints
    };
    this.games.push(game);
  }
};

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

team.addGame('Putans', 44, 45);
team.addGame('The Booleans', 24, 46);
team.addGame('Troofies', 53, 14);

console.log(team._players);
console.log(team._games);

you could make a method for nicely displaying the players?

the problem is that your getters mostly implement default behavior, so you don’t get to see the true power of getters, lets do this simple example:

const example = {
  _myArray: [1, 2, 3],
  
  get myArray(){
    return this._myArray.join('-');
  }
}

console.log(example.myArray);

i have an array, but its represented nicely as string thanks to the getters.

at the last line of my code, i call the getter, the getter then reads the value of the property (this._myArray) and manipulates the data (join)

what you need to prevent is that the property (_myArray) and the getter (myArray) have the same name, because then the getter will endlessly call itself (recursion).

the underscore is just a convention, i would advise you to use the convention, but just for demonstration purpose:

const example = {
  abc: [1, 2, 3],
  
  get def(){
    return this.abc.join('-');
  }
}

console.log(example.def);

maybe this clarifies a thing or two

1 Like

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