mardi 5 mai 2020

Javascript ternary if statement, assigning it to a variable and incrementation

So, I have this piece of code, which actually works: (hash would be an object like this: {"bob" => "12, "Roger" => "15", etc}, and isGood(key) is a calling the function isGood that just returns if the player is good or bad)

let score = 0;
Object.keys(hash).forEach((key) => {
  isGood(key) === true ? score += parseInt(hash[key], 10) : score -= parseInt(hash[key], 10);
});
return score;

for which I get this error message:

Expected an assignment or function call and instead saw an expression

And I managed to make it work without getting this error message, like this:

let score = 0;
Object.keys(hash).forEach((key) => {
  score = isGood(key) ? score + parseInt(hash[key], 10) : score - parseInt(hash[key], 10);
});
return score;

But, why would the first one not be a proper way to do it, eventhough it works? I am sorry I have problems with conventions in Javascript. Thanks in advance! Olivier

Aucun commentaire:

Enregistrer un commentaire