Why does the following code produce a == 3
?
var x = "abc";
var y = 3;
var z = "xyz";
var a = x && y || z;
http://jsfiddle.net/thinkingmedia/qBZAL/
I would have expected this to result in a == true
.
Why is the logical operator evaluating "abc"
as true
but doesn't evaluate 3
as true
. Instead it produces 3
as the result.
Furthermore, if you change y = 0
then a == "xyz"
which means that &&
treated 0
as false
. What happen to treating a number as a number?
What's going on here with the logical operators?
This is to be expected.
In JavaScript (and many other languages), not only Booleans themselves are true or false, but other objects can be truthy or falsey as well (See the docs on mdn):
The value […] is converted to a boolean value, if necessary. If value is […] is
0
,-0
,null
,false
,NaN
,undefined
, or the empty string (""
), [it is] false. All other values, including any object or the string"false"
, create […] true.
The logical operators ||
and &&
don't return true
or false
, rather they return the last argument to influence whether they are truthy or falsey (reference):
expr1 && expr2
– Returnsexpr1
if it can be converted to false; otherwise, returnsexpr2
. Thus, when used with Boolean values,&&
returns true if both operands are true; otherwise, returns false.expr1 || expr2
– Returnsexpr1
if it can be converted to true; otherwise, returnsexpr2
. Thus, when used with Boolean values,||
returns true if either operand is true; if both are false, returns false.
The first step is to evaluate "abc" && 3
.
false && 3
would return false
,true && 3
would return 3
."abc" is not false, so JavaScript takes the second part, i.e. 3.
The second step is to evaluate 3 || "xyz"
. Here, JavaScript takes the first value which is not null, i.e. 3. This is similar to this.firstObject ?? this.defaultValue
in C#: the second part is taken only when the first part is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With