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?