0

Can someone explain to me why ... (this is in the chrome console)

null == false //false

!null == false //false

[] ? 'hello' : 'goodbye' //'hello'

[] == true ? 'hello' : 'goodbye' //'goodbye'

I could come up with a bunch more, but basically how does javascript arrive at these results?

Ryan Dignard
  • 639
  • 1
  • 5
  • 16
  • possible duplicate of [JavaScript type casting](http://stackoverflow.com/questions/4626361/javascript-type-casting) – Bergi Aug 29 '13 at 00:26

3 Answers3

2

JavaScript does a lot of type casting which is not apparent without knowing it (JavaScript equality transitivity is weird).

The ! NOT operator, the Boolean function, the ? : ternary operator, if-clauses and the logical AND/OR operators do use the internal ToBoolean conversion - it is what is producing our understanding of the falsy value 0, NaN, "", null, undefined and false.

However, when you are comparing things the (non-strict) equality comparsion algorithm comes into play, which produces some seemingly odd results when comparing diagonal types with each other. In your case:

  • null is only equal to itself or undefined but not to false
  • When you are comparing an array object to a boolean, it is getting more complicated. Booleans get compared to other types as if they were numbers, i.e. true is casted to 1 first. Then, when an object is compared to a number, it will be casted to a primitive value (without a preferred type) - invoking the DefaultValue algorithm which essentially is calling the arrays' .toString method which will .join() it. So [] is casted to "" - which then is passed to ToNumber since it will be compared against 1. In the end 0 is not 1. However, [] == false and [1] == true or ["1"] == true hold…
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

magic *waves hands mysteriously*

On a more serious note, for the first two, the ! operator calls toBoolean on null, so if you checked !null == !false or !!null == false you should get true. Similar things are likely happening in the other cases.

With information provided by Tore Hanssen, we can answer the other two as well. [] is a 'truthy' value, but not a boolean, so directly comparing it to true returns false. However, you could use the ! operator again to make it a boolean, so !![] == true returns true!

Jordan
  • 1,433
  • 8
  • 14
  • 1
    with the other cases, an empty array is not undefined or null, so it returns true, but it is not a boolean == true, so thats why it says goodbye – Tore Aug 28 '13 at 23:53
  • @ToreHanssen Ah, so it is something similar then :) Thanks for letting me know! – Jordan Aug 28 '13 at 23:55
0

There is an interesting post on this topic here: http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

In some of your examples, to force coercion, just using "==" is not enough.

!!null == false

!![]

!![] == true

cababunga
  • 3,090
  • 15
  • 23