为何0与布尔值进行&&运算返回0而非布尔值?
&& and boolean values? Great question! This behavior boils down to two key concepts: short-circuit evaluation for the logical AND (&&) operator, and operator precedence. Let’s break down your examples one by one to clear up the confusion.
Core Rule of the && Operator
In languages like JavaScript (and many others), the && operator doesn’t always return a boolean. Instead, it follows this logic:
- It evaluates operands from left to right.
- As soon as it hits a falsy value (0,
false,"",null,undefined,NaN), it returns that falsy value immediately—no need to check the right operand. - If all operands are truthy (anything not falsy), it returns the last truthy operand.
This is called short-circuit evaluation: it stops calculating as soon as the final result is determined.
Let’s Walk Through Your Examples
First, remember that comparison operators like > have higher precedence than &&, so they get evaluated first.
1. 0 && false > 0
- Step 1: Evaluate
false > 0. When booleans are compared to numbers, they convert to numeric values:falsebecomes0, so0 > 0results infalse. - Step 2: The expression simplifies to
0 && false. Since0is a falsy value,&&returns0right away.
2. 0 && true > 0
- Step 1: Evaluate
true > 0.trueconverts to1, so1 > 0results intrue. - Step 2: The expression becomes
0 && true.0is falsy, so the operator returns0.
3. false && 0
- Here,
falseis the left operand and it’s falsy.&&returnsfalseimmediately—we never even evaluate the0on the right.
4. true && 0
Quick correction here: this should return 0 (not true as you mentioned). Here’s why:
trueis truthy, so&&moves to evaluate the right operand0.0is falsy, so the operator returns0. If you saw it returntrue, that might be a typo or confusion with the||operator (which returns the first truthy value, liketrue || 0→true).
5. false && 0 > false
- Step 1: Evaluate
0 > false.falseconverts to0, so0 > 0results infalse. - Step 2: The expression simplifies to
false && false.falseis falsy, so the operator returnsfalse.
Clearing Up Your Original Misconception
You assumed that numeric and boolean expressions with && always return a boolean, but that’s not the case. The && operator returns the actual operand value (falsy or truthy), not a converted boolean. It only acts like a boolean when used in a boolean context (like an if statement), where the return value gets coerced to a boolean automatically.
For example:
1 && falsereturnsfalse(a boolean) because1is truthy, so it returns the right operandfalse.1 && false > falseworks out to1 && (false > false)→1 && false→false.
内容的提问来源于stack exchange,提问作者Radha Satam

