Why if([]) is validated while [] == false in javascript?

Both current answers here are correct, but I’d like to add a more detalied explanation based on the language specification. The reason for the apparently contradictory outcomes is that if statements and equality comparisons are evaluated differently.

In the case of an if(expression) statement, the expression is evaluated and then converted to the boolean type (§ 12.5). Arrays are Objects, and when an Object is converted to Boolean, the result is always true (§ 9.2).

Equality comparisons with == follow a different set of rules, detailed on § 11.9.3. The comparison may require multiple type conversions, until both operands are the same type. The order of the operands is also important. According to that algorithm, we can see that the comparison [] == false is actually a four-step operation:

  1. There is a Boolean involved, so it’s converted to a Number first (step 7 of the algorithm). So it becomes:

    [] == 0
    
  2. Then the array is converted to its primitive value (see § 9.1 and § 8.12.8), and becomes an empty string (step 9). So:

    "" == 0
    
  3. When comparing a String to a Number, the String is converted to Number first (step 5, following the rules described on § 9.3.1):

    0 == 0
    
  4. Now that we have two Numbers, the comparison evaluates to true according to step 1.c.iii.

Leave a Comment