为何return无需if语句就能返回true或false?附代码示例解析
Hey there! Great question—let’s break this down clearly so it makes sense.
First, let’s recap your two examples to set the stage:
Example 1 (Explicit if/else):
function isEven(){ if(num % 2 === 0){ return true; } else { return false; } }
This function works by explicitly checking the condition num % 2 === 0. If that condition is true, it returns true; if not, it returns false. It’s a very straightforward, "spell everything out" approach.
Example 2 (Direct Return of Expression):
function isEven(){ return num % 2 === 0 }
The key here is understanding that comparison expressions in JavaScript already return a boolean value (true or false) on their own. Let’s unpack what num % 2 === 0 does step by step:
num % 2calculates the remainder whennumis divided by 2. For even numbers, this remainder is 0; for odd numbers, it’s 1 (or -1 for negative odds, but the equality check still holds).- The
===operator compares that remainder to 0. This comparison doesn’t just check equality—it outputs a boolean:trueif the remainder is 0,falseif it’s not.
So instead of using an if/else to take that boolean result and return the same value (which is redundant), Example 2 skips the middleman and returns the comparison’s result directly. It does exactly the same thing as Example 1—just in a more concise way.
Think of it like this: Example 1 says "If X is true, give me true; else give me false." Example 2 just says "Give me the result of X being true or false." Since X already is a true/false value, both do the exact same work.
内容的提问来源于stack exchange,提问作者Nadav Himmelfarb

