Why do both "[] == true" and "![] == true" evaluate to false?

It's the way coercion works.

The first step of coercion is to convert any non primitive types to primitive types, then using a set of rules convert the left, right or both sides to the same type. You can find these rules here.

In your case [] == true, would pass through these 4 steps:

  1. [] == true
  2. [] == 1
  3. "" == 1
  4. 0 == 1

Whereas based on operator precedence the ! in ![] == true is executed first so the expression is converted to false == true which is obviously false.

You can try the live demo by Felix Kling to better understand how the sameness operator works.


As per the Abstract Equality Comparison Algorithm - http://es5.github.io/#x11.9.3

Types of x and y are checked when x == y is to be checked.

If no rule matches, a false is returned.

  1. For [] == true , rule 7 matches, so a result of [] == ToNumber(true) is returned i.e. false is returned.
  2. Reason you're getting the same result for ![] == true, because ![] returns false, and false == true returns false .

To get opposite result for your second operation, add a precedence (i.e. wrap) to your expression with braces.

console.log(!([] == true)); // returns true

Tags:

Javascript