0

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?

7
  • 4
    5 will get converted to false ? Commented Oct 21, 2015 at 17:33
  • How does the question you linked to relate to your question? Commented Oct 21, 2015 at 17:33
  • Because (5 == !0) is equivalent to (5 == true), which is false. Commented Oct 21, 2015 at 17:36
  • @j08691 it was just for background, its the reason why I tried the things in the console. Commented Oct 21, 2015 at 17:37
  • 1
    @j08691 More specifically 5 == 1 is false. The moral of the story is don't rely on == to do the conversion that you expect it to OP, it's quite funky. Commented Oct 21, 2015 at 17:41

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh! yes 1 == !0 gives true.
x == ToNumber(y) would happen only if x is a number isn't it?
@AkshendraPratap: Sort of. The algorithm is recursive. So x could start off as something else but have been converted to a number on an earlier pass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.