admin管理员组文章数量:1312774
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;
本文标签: How do I return true or false for ternary operator in JavascriptStack Overflow
版权声明:本文标题:How do I return true or false for ternary operator in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741880769a2402731.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论