Team Stats: Javascript Objects

Is there a reason why the .push() function is not working in the code below? The error I get is “TypeError: Cannot read property ‘push’ of undefined at Object.addPlayer”. I’ve even copied the examples and the video word for word (Unless I missed something completely obvious)

const team = {  
  _players: [
    {firstName: 'Pablo',lastName: 'Sanchez',age: 11},
    {firstName: 'Sam',lastName: 'Bingo',age: 11},
    {firstName: 'Paul',lastName: 'Bongo',age: 11},
  _games: [
    {opponent: 'Broncos',teamPoints: 42,opponentPoints: 27},
    {opponent: 'Wolves',teamPoints: 13,opponentPoints: 64},
    {opponent: 'Turtles',teamPoints: 20,opponentPoints: 21},
  get _players() {
    return this._players;
  get _games() {
    return this._games;
  addPlayer(firstName, lastName, age) {
    let player = {
      firstName: firstName,
      lastName: lastName,
      age: age


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


There are two issues:

  1. Your getters are named wrong.
  2. You’re trying to call players which doesn’t exist.

You’ve replaced the value of _players from the array to the getter method and same for _games. This means that when you call _players and _games you are entering an infinate recursive loop beacuse it keeps calling itself with this._players.

The error you are getting is because in addPlayer you are trying to call this.players with no “_” before players, which you haven’t defined yet; however, this is what the getter for _players would be called.

Lastly lets look at the error returned to see how that helps us solve the issue. - “Cannot read property push of undefined at Object.addPlayer”
Ok, so we are using trying to call push on something that doesn’t exist and we tried to do it in addPlayer.

  1. Where did we used push in addPlayer? this.players.push(player)
  2. We know where you used it, what did we use it on? this.players
  3. So we were expecting something called players to exist in the object in which addPlayer is defined but it didn’t, why? Because it is never defined.

After solving this error we would have got a second about the getters calling them self in an infinite loop, but it would have got us a step dcloser to debugging the code.

1 Like

Thank you for the reply! That definitely makes sense. I was able to resolve and run the code just by removing the “_” from the getters. The code successfully ran at that point. It’s always the little things! haha.

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