简体   繁体   中英

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

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.

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 comparison without ternary.

return sum % 10 === 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM