3

If i execute the following lines in thw browser console

!![] //--- returns true
!!0 //--- returns false

I get that [] and 0 have different boolean values.

I don't understand why

[] == 0 //--- returns true

returns true.

What am I missing?

BeNdErR
  • 17,471
  • 21
  • 72
  • 103

2 Answers2

6

Remember that array is object and 0 is number.

And as "user2864740" told..

1) When you doing

!![] //--- returns true
!!0 //--- returns false

You are performing so called "ToBoolean" convertion

https://es5.github.io/#x9.2

Number

The result is false if the argument is +0, −0, or NaN; otherwise the result is true.

Object ( our [] )

always true

2) But when you using == you performing so called "Equality Comparison"

https://es5.github.io/#x11.9.3

Here thins a little bit complicated but to understand what happens you have to remember that == do a type coercion ( so you can compare oranges to apples :) )

First of all compiler converts [] to some primitive type.

If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

How ToPrimitive works is a matter of an article :), but's it easy to remember that closet primitive type to array is string. Array will be converted to empty string.

[].toString() === ""

So now we need to compare empty string and number 0

"" == 0   // true

Hmmm. So it's true. But why is that? Remember that when you compare with "Equality Comparison" number and string

  1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

So let's try to convert empty string to number

Number("") === 0

And in the end

0 === 0

I hope that's explains something :)

obenjiro
  • 3,665
  • 7
  • 44
  • 82
1

JavaScript is probably converting the array to a number:
!!Number([]) // false
Number([]) == 0 // true

G_hi3
  • 588
  • 5
  • 22