tags:

views:

157

answers:

4

Why both

 [] == false

and

![] == false

are true?

+10  A: 

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

Anthony Mills
Although your answer is helpful it doesn't answer the question.
Georg
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
+6  A: 

"For the ! operator, if expression is nonzero, result is zero. If expression is zero, result is 1." (link)

First, [] is inherently false.

Since the expression [] is nonzero, then the result of ![] is zero.

Therefore, ![] == false evaluates to 0 == false which evaluates to true.

Steven
The ! operator returns true or false, not 1 or 0.
Anthony Mills
`[]` is not inherently false.
Crescent Fresh
+4  A: 

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".

Dave
[] is not falsey. It's a side effect of string coercion.The array [''] is also == false, but is not falsey.
Mike Samuel
@mikesamuel thanks for the insight!
Dave
+2  A: 

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
why would a list be coerced to string when compared with a boolean value? Any sources?
luntain
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