What’s the difference between:
!!(obj1 && obj2);
and
(obj1 && obj2);
What’s the difference between:
!!(obj1 && obj2);
and
(obj1 && obj2);
The first will potentially return a string or an object, the second will return a boolean.
Because objects can be truthy in javascript, A && B
will return the value of B
if it is truthy, which may be an object. But using !! will cast it to a boolean because the !B will convert it to true or false, and the second ! will move it to the correct boolean value
An example where the two will differ:
var a = "test", b ="example"
var ex1 = ((a && b) === true) // false
var ex2 = (!!(a && b) === true) // true
There is none.
In general, !!
is used to cast to boolean without using a function call, similar to how 0^
can be used to cast to integer, ""+
can be used to cast to string, etc.
However, in this case, assuming it's inside an if
statement, there's no difference at all since the if
implicitly "casts" to a boolean to see if it's true or not.