Reputation: 12532
Specifically (I don't know if it can happen in others case), when I do int(0) && boolean
with myString.length && myString === "true"
when myString = ""
, it returns 0
instead of returns a boolean.
alert((function() {
var myString = "";
return myString.length && myString === "true";
})());
I know that I can fix it by do myString.length !== 0
or casting with Boolean
. But I like to understand why &&
don't force cast the left side to boolean.
Live example: http://jsfiddle.net/uqma4ahm/1/
Upvotes: 2
Views: 37
Reputation: 61875
The &&
operator yields the left hand value if it is false-y1 and the right-hand value otherwise. (Unlike some languages, it is not guaranteed to evaluate to true or false!)
TTL for A && B:
A B (A && B)
false-y - A
truth-y - B
To make sure that only true or false is returned, it is easy to apply (double) negation:
return !!(myString.length && myString === "true")
or, equivalently
return !(!myString.length || myString !== "true")
Here is the negation TTL which leads to deriving !!(false-y) => false
and !!(truth-y) => true
.
A !A !(!A)
false-y true false
truth-y false true
1 In JavaScript the false-y values are false 0, "", null, undefined, NaN. While everything else is truth-y.
Upvotes: 3
Reputation: 413712
The &&
operator in JavaScript returns the actual value of whichever one of its subexpression operands is last evaluated. In your case, when .length
is 0
, that expression is the last to be evaluated because 0
is "falsy".
The operator does perform a coercion to boolean of the subexpression value(s), but it only uses that result to determine how to proceed. The overall value of the &&
is thus not necessarily boolean; it will be boolean only when the last subexpression evaluated had a boolean result.
This JavaScript behavior is distinctly different from the behavior of the similar operator in C, C++, Java, etc.
Upvotes: 4