Logical AND (&&
) and OR (||
) operators --- who knew they could trick us like this :)
Their definition, for JS (according to this explanation), is the following:
expr1 && expr2 => Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
expr1 || expr2 => Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
Testing it, indeed it works just as the definition, but here's the problem:
false || "" //returns ""
"" || false //returns false
So, obviously:
(false || "") == ("" || false) // true
But, sadly
(false || "") === ("" || false) // false
To the main two questions:
- Is this a bug, or why is JavaScript forcing us to use
==
operator or to pay attention to the order when using&&
and||
operators? - Why is javascript unable to convert expr1 to
true
in this expression("" || false)
?. I mean, isn't it as simple as prepending""
with the NOT (!
) operator?