最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I return true or false for ternary operator in Javascript? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

The 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;
发布评论

评论列表(0)

  1. 暂无评论