Yugo Kamo
Yugo Kamo

Reputation: 2389

Array and if statements

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.

Upvotes: 1

Views: 421

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185933

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

Upvotes: 1

Aleadam
Aleadam

Reputation: 40391

You can find some answers in here:

Strangest language feature

JavaScript equality transitivity is weird

Upvotes: 0

Justin Thomas
Justin Thomas

Reputation: 5848

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

Upvotes: 0

Related Questions