0

I am trying to make a basic score tracker using JavaScript:

function Player(name) {
    this.name = name;
    this.scores = [];
}

function addPlayer(name) {
    playersList.push(new Player(name));
    return playersList;
}

function addScore(name, score) {
    playersList.forEach(player => {
        if (player.name == name) {
            player.scores.push(score);
        };
    });
}

function getTotal(name) {
    playersList.forEach(player => {
        if (player.name == name) {
            let sum = 0;
            player.scores.forEach(score => sum += score);
            console.log(sum);
        } 
    });
}

var playersList = [];
addPlayer("Player1");
addScore("Player1", 3);
addScore("Player1", 4);
console.log(getTotal("Player1"));

The output I am expecting is:

7
7

but instead I get:

7
undefined

Could anyone help me as to why my console.log() does not log the number returned from the function?

naznsan
  • 3
  • 1

1 Answers1

0

Try this one

function getTotal(name) {
  let sum = 0;
  playersList.forEach(player => {
    if (player.name == name) {        
        player.scores.forEach(score => sum += score);
        console.log(sum);
    } 
  });
  return sum
}
  • Thanks for this, it works the way I want it to. Could you possibly help me figure out why this works? Is it because the `let` keyword declared `sum` only inside the `if` block? – naznsan Apr 17 '20 at 02:32
  • I'm not expert at this but you can refer to this link. https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function. You need to declare variable outside the forEach, then you manipulate that variable inside, if so you can return the total sum in the end of function. Cuz you cannot return something in forEach, doing so will not break the loop – Galang Piliang Apr 17 '20 at 10:54