Search code examples
javascriptobjectif-statementassignternary

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


Solution

  • It is valid JavaScript code. I believe the error messages comes from jshint, which is a linter.

    Here is a related answer: Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression

    In the end it is a matter of style, but having side-effects in a ternary operator is unexpected, which explains why a linter has rules to point it out. It makes it harder to reason about the code, so you would normally see an if-then-else construct instead.