Team stats: When iterating over _players, last item of "for"-loop is undefined


Team Stats

Full code:



After successfully completing the Team Stats project, I decided to play a bit with the code.

To retrieve the player names and age and then display them using template literals, I added a method displayPlayers() to the team object. This method consists of a “for”-loop that iterates through the objects in _players. Instead of only returning the desired output, an additional last item of undefined is returned.

  displayPlayers() {
    for (let i = 0; i < this._players.length; i++) {
      const firstName = team._players[i].firstName;
      const lastName = team._players[i].lastName;
      const age = team._players[i].age;
      console.log(`${firstName} ${lastName} is ${age} years old`);
Max Blah is 16 years old
Maria Blub is 21 years old
Josef Blii is 26 years old

What needs to be changed in order to generate the desired output? Thank you!


You try to print to console result of displayPlayers method, but you haven’t return statement in it. Without explicitly return every method will return undefined.

So the problem is not in the loop, but in last statement of entire code: console.log(team.displayPlayers());. You try to print result of method which doesn’t return any result.

The easiest solution is simply remove last console.log().

Hope this will help.

1 Like

Thanks for the solution! Late at night I was too tired to realize that just invoking the method would already log to the console :sweat_smile: