javascript - Logical AND (&&) and OR (||) operators -
logical , (&&
) , or (||
) operators --- knew trick :)
their definition, js (according this explanation), following:
expr1 && expr2 => returns expr1 if can converted false; otherwise, returns expr2. thus, when used boolean values, && returns true if both operands true; otherwise, returns false.
expr1 || expr2 => returns expr1 if can converted true; otherwise, returns expr2. thus, when used boolean values, || returns true if either operand true; if both false, returns false.
testing it, indeed works definition, here's problem:
false || "" //returns "" "" || false //returns false
so, obviously:
(false || "") == ("" || false) // true
but, sadly
(false || "") === ("" || false) // false
to main 2 questions:
- is bug, or why javascript forcing use
==
operator or pay attention order when using&&
,||
operators? - why javascript unable convert expr1
true
in expression("" || false)
?. mean, isn't simple prepending""
not (!
) operator?
it's how work. it's not bug:
returns expr1 if can converted false; otherwise, returns expr2
this means can use "default values", this:
function somefunc(passedparameter){ var newvalue = passedparameter || 1337 }
or run functions when conditions met:
var mybool = true; mybool && somefunc(); // somefunc evaluated if `mybool` truthy
Comments
Post a Comment