13

Why both

 [] == false

and

![] == false

are true?

luntain
  • 4,560
  • 6
  • 37
  • 48

3 Answers3

15

The === operator is your friend. Never use the == operator; it will bite you, as you can see.

Anthony Mills
  • 8,676
  • 4
  • 32
  • 51
  • 9
    Although your answer is helpful it doesn't answer the question. – Georg Schölly Oct 07 '09 at 20:35
  • 3
    True. The values that are "false" are: undefined, null, false, 0, and "". As mikesamuel says, [] coerces to "". So much for the first one. And a non-null object reference is true, which answers the second one. – Anthony Mills Oct 07 '09 at 22:04
11

An empty list, [] must be considered a "falsey", however in ![] the ! is then converting the operation to check for an object reference, where a non-null is not considered a "falsey".

David
  • 19,389
  • 12
  • 63
  • 87
5

Before [] is compared to false, it is coerced to a string which is coerced to a number, the empty string in the case of the empty array. The empty string coerces to 0 which is the same value that false coerces to numerically.

Use === instead of == to avoid this problem

These other arrays are also falsey:

  ['']
  [[[]]]
  (function () { var arr = []; arr[0] = arr; })()
  [0]
  ['-0.0']
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • why would a list be coerced to string when compared with a boolean value? Any sources? – luntain Oct 14 '09 at 16:25
  • From section 11.9.3 of EcmaScript 262: 18. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. 19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). Then coercing an Array to a number consists of first coercing it to a string and then coercing that string to a number. For most arrays, that will yield the non-comparable value NaN, but for some arrays, [], [0], [[0]], ['0.0'], etc. they will compare truthfully with false. You can experimient with the coercion behavior by evaluating (+[0]) etc. – Mike Samuel Oct 15 '09 at 17:38