Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj &&
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:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
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:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
entire condition is false, so return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean()
function, like this:
var a = Boolean(1 || 2 || 3);// a = true