Codegiant
Codegiant

Reputation: 2150

Need to explain the term [0] == ![0]

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

Upvotes: 1

Views: 560

Answers (3)

raina77ow
raina77ow

Reputation: 106385

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? )

Upvotes: 7

grundprinzip
grundprinzip

Reputation: 2491

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.

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

![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.

Upvotes: 8

Related Questions