1
if([]){}//true
if([]==true){}//false
if([1]==true){}//true
if([2]==true){}//false
if([1,2]==true){}//false
if(['Hi']==true){}//false
if([{aaa:1}]==true){}//false

[ ] is array. Array is object. Object is true, so [ ] is true. This is OK.

But I can't understand other results.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Yugo Kamo
  • 2,349
  • 4
  • 18
  • 13
  • Agreed - don't expect people to help if you aren't going to follow the SO protocol of ask/answer/accept. (We aren't expecting 100% accept, but 0% is ridiculous) – Jamie Wong Mar 28 '11 at 17:29
  • An empty array `[]` coerces to the Number value `0` I believe. – Šime Vidas Mar 28 '11 at 17:34

3 Answers3

1
if([]){}//true

All JavaScript objects are truthy - they all coerce to the Boolean value true.


if([]==true){}//false

If one Operand is an Object, and the other operand is a Boolean, then both operands coerce to a Number value. An empty array will coerce to 0:

0 == 1 // false

if([1]==true){}//true

Same thing here. For an array with one item, that item will coerce to Number and that value will be compared to the other operand:

1 == 1 // true

if([2]==true){}//false

is:

2 == 1 // false

if([1,2]==true){}//false

If the array has multiple items, the coercion to Number will result in NaN:

NaN == 1 // false

if(['Hi']==true){}//false

The string coerces to the Number value NaN:

NaN == 1 // false

if([{aaa:1}]==true){}//false

An object also coerces to the Number value NaN:

NaN == 1 // false
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • That's good stuff, is there a reference or easy way to test for myself what coercion is happening? – Ryley Mar 28 '11 at 18:21
  • @Ryley Just read the spec: http://es5.github.com/#x11.9.3 It says it all right there. The coercion rules are 4. - 9. – Šime Vidas Mar 28 '11 at 18:25
  • Perfect, I just wanted to make sure that info got attached to this answer :) – Ryley Mar 28 '11 at 18:28
0
if([]==true){}//false

[ ] is not a boolean true it's an array. That is saying that an empty array IS a boolean true. It isn't--it's an empty array.

if([]) {} evaluates it as being defined and not null.

Check this: http://11heavens.com/falsy-and-truthy-in-javascript

Justin Thomas
  • 5,680
  • 3
  • 38
  • 63
  • That is correct, although it does not explain why `if([1]==true){}//true` . For what I understand, `[1]` is `1` which is `true` – Aleadam Mar 28 '11 at 17:37
0

You can find some answers in here:

Strangest language feature

JavaScript equality transitivity is weird

Community
  • 1
  • 1
Aleadam
  • 40,203
  • 9
  • 86
  • 108