Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn()
(if it is defined) OR obj._
but not boolean result.
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign
true
orfalse
value. Rather it assigns the calculated value.Let's have a look at this expression.
An example expression:
Your expression:
Another expression:
Another expression:
In most programming languages, the
&&
and||
operators returns boolean. In JavaScript it's different.OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
Example 2:
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
Example 2:
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use
Boolean()
function, like this:Compare:
with:
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.
In the simplest terms:
The
||
operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).The
&&
operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).It's really that simple. Experiment in your console to see for yourself.
You could use !! before the condition to get the Boolean result.
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of: