Search code examples
javascripttype-conversioncoercion

JavaScript - Why does +!{}[0] == 1?


I found an interesting JavaScript question online. It was what does +!{}[0] equal?

The answer really surprised me and turned out to be 1.

Now I'm trying to understand why this syntax would result in that.

That's why I tried to break it down

!{} returns false

false[0] returns undefined

+false[0] returns NaN

So I can't understand why that above expression would return 1. Any theories?


Solution

  • You have the precedence of the operators wrong (MDN). It is:

    {}[0] returns undefined

    !undefined returns true

    +true returns 1