Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `[] == false` is true but just `[]` evaluates to true? [duplicate]

Tags:

javascript

The following prints 'A' as expected, since the data type is different so the array is coaxed into a primitive form which is false for empty arrays.

if ([] == false)
    console.log('A');
else
    console.log('B');

But then why the following code too prints 'A'?

if ([])
    console.log('A');
else
    console.log('B');
like image 846
AppleGrew Avatar asked Mar 06 '14 17:03

AppleGrew


3 Answers

Why is [] == false is true

Because arrays behave oddly when compared to primitive values.

In particular, when you compare any non-boolean to a boolean, the boolean is handled as a number. Then, when you compare a number to an object the object is converted to a primitive - which stringifies the array before again comparing it to the number. Now, that string is converted to a number so that they can be compared:

[] == false
[] == 0
"" == 0
0 == 0

Similarly, you can try

[1] == true
[1] == 1
"1" == 1
1 == 1

or

[2] == true
[2] == 1
"2" == 1
2 == 1

but just [] evaluates to true?

Because any object is truthy.

like image 129
Bergi Avatar answered Oct 11 '22 00:10

Bergi


The == operator forces a type cast. [] as boolean is false. Why doesn't the same happen with eg. "a" == false? Basically, the numeric value of [] is 0, while the numeric value of "a" is NaN. Predictably, "0" == false is true :)

On the other hand, in the second case, you're basically just checking if [] exists ("isn't null"). There is no casting to boolean.

like image 21
Luaan Avatar answered Oct 11 '22 00:10

Luaan


The first test returns true because of these equality rules :

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.

(and yes, you do have [].toString()=="" and thus []==0)

The second test

if ([])

simply is passed because all objects are truish.

like image 37
Denys Séguret Avatar answered Oct 10 '22 23:10

Denys Séguret