I'm trying to convert the code below to a shorthand version with a ternary operator
if (sum % 10 === 0) {
return true;
} else {
return false;
}
It works fine as is, but when I change it to
sum % 10 === 0 ? return true : return false;
I get a syntax error, and when I change it to
sum % 10 === 0 ? true : false;
it doesn't work as intended.
If anyone can enlighten me as to what's going on, I'd be much appreciated.
What you tried:
sum % 10 === 0 ? return true : return false;
This does not work, because return
is a statement and not an expression. A statement can not be used inside of an expression.
sum % 10 === 0 ? true : false;
This works, but without a return
statement, it is just an expression without using it.
Finally, you need to return the result of the conditional (ternary) operator ?:
, like
return sum % 10 === 0 ? true : false;
For a shorter approach you could return the result of the comparison without ternary.
return sum % 10 === 0;