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.

2
  • 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) Commented Mar 28, 2011 at 17:29
  • An empty array [] coerces to the Number value 0 I believe. Commented Mar 28, 2011 at 17:34

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

That's good stuff, is there a reference or easy way to test for myself what coercion is happening?
@Ryley Just read the spec: es5.github.com/#x11.9.3 It says it all right there. The coercion rules are 4. - 9.
Perfect, I just wanted to make sure that info got attached to this answer :)
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

1 Comment

That is correct, although it does not explain why if([1]==true){}//true . For what I understand, [1] is 1 which is true
0

You can find some answers in here:

Strangest language feature

JavaScript equality transitivity is weird

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.