Reputation: 2040
I was tring a few things in the console.
!5 is actually false
0 is a falsy value, so
0 == !5 is true
Okay, but when i tried this
!0 is true
5 is a truthy, so
5 == !0 should be true
But its not, the console says false. Why is this happening?
Upvotes: 0
Views: 63
Reputation:
The reason the last line is false
is that the ==
isn't a simple boolean conversion. It usually tries to convert operands with non-matching types down to a number.
So the 5
doesn't need conversion since it's already a number but !0
, which is true
, does. The value true
gets converted to 1
, so it doesn't equal 5
.
You can infer from this that 1 == !0
will be true
, and indeed it is.
This is detailed in the ES5 spec in the Abstract Equality Comparison Algorithm, step 7, which says of the comparison x == y
:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
So the right-hand boolean is coerced to a number with ToNumber. In this case, ToNumber says:
The result is 1 if the argument is true.
Upvotes: 5