The general solution for this in javascript is to use !!
to parse to a boolean. !!
negates the truthiness twice, resulting in a boolean which has the same truthiness of the original.
You should then use &&
as a logical and
operation.
var a=null;
var b=true;
console.log(!!a && !!b); // false
Edit: An addendum on the strange +
behaviour
The strangeness you're seeing when using +
instead of &&
is because, in JavaScript, +
coerces booleans to integers, with true
becoming 1
and false
becoming 0
.
Hence
true + true \\ 2
true + false \\ 1
And then when doing
true + true == true
the left-hand-side of the equality comparison resolves to 2
, JavaScript then coerces the right-hand-side to 1
and thus the equality check fails.
When doing
null + true == true
the left-hand-side becomes the integer 1
, and then so does the right.
I'd recommend reading the MDN guide on Equality comparisons and sameness for more on JavaScript's value coercion and abstract equality checks.
true + true == 2
becausetrue
is the same as1
(but not strictly). So of course2 != true
a+b
, variables are converted to integers.a+b
is 2. 2 is nottrue
sincetrue
is converted to 1.