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.
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.
Share Improve this question edited Apr 17, 2020 at 6:40 Nina Scholz 387k26 gold badges363 silver badges413 bronze badges asked Apr 16, 2020 at 8:02 Steve KimSteve Kim 331 silver badge3 bronze badges 4-
5
return sum % 10 === 0 ? true : false;
– Sajeeb Ahamed Commented Apr 16, 2020 at 8:03 -
4
Even
return sum % 10 === 0
should be fine – Anurag Srivastava Commented Apr 16, 2020 at 8:03 -
2
return sun % 10 === 0;
If the condition is true, will return true, if the condition is false, will return false. – KodeFor.Me Commented Apr 16, 2020 at 8:04 - 1 "If anyone can enlighten me..." -> Conditional (ternary) operator - JavaScript | MDN – Andreas Commented Apr 16, 2020 at 8:06
3 Answers
Reset to default 6The expression (sum % 10 === 0)
is boolean itself, so just return it:
return sum % 10 === 0
You can simply do:
return !(sum % 10)
if (sum % 10) === 0
, then !(sum % 10)
will return true
, else false
.
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 retur 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 parison without ternary.
return sum % 10 === 0;