1

what does the term [0] == ![0] means? Though they return true.But i need to explain how it returns true as type of [0] is object and ![0] returns boolean? So how they are equal? Thanks

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
Codegiant
  • 2,110
  • 1
  • 22
  • 31

3 Answers3

8

![0] is simply false, since all non-null objects cast to true.

When comparing [0] and false, they are converted to numbers - don't ask why, that's just the way it is. [0] is first converted to the string "0" (arrays cast to strings by concatenating the entries with , for a separator), which is then the number 0. false is cast to the number 0, and there you have it: [0] == ![0] is equivalent to 0 == 0, which is true.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
7

To understand this, go through ![0] expression first. It evaluates to false - as [0] (as any Object in JS) is a truthy value. So the statement becomes...

[0] == false

Now it's easier: false is converted to 0 (for Boolean -> Number rule), and [0] is converted by Object-To-Primitive rule - first to '0' (String), then to 0 (Number). Obviously, 0 is equal to 0. )

P.S. And yes, it may seem quite weird, but both...

[0] == false

... and ...

![0] == false

... evaluate to true: the former is already explained, the latter is just false == false. Anyone still surprised by those == Lint warnings? )

raina77ow
  • 103,633
  • 15
  • 192
  • 229
-1

You have split the expression into multiple parts:

typeof([0]) // "object"
[0] == true // false
![0] == true // false
![0] == false // true

The reason for this because in JavaScript only the value 1 is implicitly converted to true, so all other values are converted to false. The ![0] only negates a false expression thus it becomes (false == false) == true.

grundprinzip
  • 2,471
  • 1
  • 20
  • 34
  • 1
    `only the value 1 is implicitly converted to true` - what? Actually, it's right the opposite: Boolean is converted to Number in comparisons. – raina77ow Jan 29 '13 at 20:42
  • What do you mean by "only the value 1 is implicitly converted to true"? That seems... not correct? Otherwise, a not unreasonable answer. – apsillers Jan 29 '13 at 20:42