Conflicting boolean values of an empty JavaScript array

The first one:

[] == false

The == operator does type conversion to its operands, in this case the both sides are converted to Number, the steps taken on the Abstract Equality Comparison Algorithm would be:

  • object == boolean
  • object == number
  • string == number
  • number == number

In code:

[] == false; // convert false to Number
[] == 0;     // convert [] to Primitive (toString/valueOf)
"" == 0;     // convert "" to Number
0  == 0;     // end

The second comparison, [] is converted to primitive, their valueOf and toString methods are executed, but since valueOf on Array objects, returns the object itself (is inherited from Object.prototype), then the toString method is used.

At the end as you see, both operands are converted to Number, and both yield zero, for example:

Number([]) == 0;
Number(false) == 0;

And empty array produces zero when converted to Number because its string representation is an empty string:

[].toString(); // ""

And an empty string converted to Number, yields zero:

+""; // 0

Now, the double negation (!![]) produces true because all object instances are truthy:

![];  // false, [] is truthy
!![]; // true, negation

The only values that are falsey are:

  • null
  • undefined
  • 0
  • NaN
  • "" (an empty string)
  • false

Anything else will produce true when converted to Boolean.

See also:

  • JavaScript Coercion Tool

Leave a Comment