Reputation: 66334
JavaScript has different equality comparison operators
==
===
It also has a logical NOT !
and I've tended to think of using a double logical NOT, !!x
, as basically the same as true == x
.
However I know this is not always the case, e.g. x = []
because []
is truthy for !
but falsy for ==
.
So, for which x
s would (true == x) === !!x
give false? Alternatively, what is falsy by ==
but not !!
(or vice versa)?
Upvotes: 2
Views: 1126
Reputation: 48761
"So, for which
x
s would(true == x) === !!x
givefalse
?"
Any x
where its Boolean conversion is not the same as its conversion by the Abstract Equality Comparison Algorithm.
An example is a string with only whitespace:
var x = " ";
Its Boolean conversion is true
(as is the case with any non-empty string), but its ==
comparison is false
because a string with only white space will be converted to the number 0
, and the true
value will be converted to the number 1
, and those values are not equal.
x == true; // false
!!x; // true
or to show the ultimate values the ==
is comparing:
Number(true) == Number(x);
// 1 == 0
1 == 0; // false
and to show the result of !!x
, it would be equivalent to this:
Boolean(x); // true
So your original expression could crudely be seen as the following:
var x = " ";
(Number(true) == Number(x)) === Boolean(x);
// ( 1 == 0 ) === true
// ( false ) === true
false === true; // false
I say "crudely" because this certainly doesn't capture all the detail of the algorithm linked above, and won't be the same for all values provided to the operands.
To understand how ==
treats its operands, you really need to study the algorithm a bit.
Upvotes: 8