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

281 views Asked by At

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?

2

There are 2 answers

3
basilikum On BEST ANSWER

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

{}[0] returns undefined

!undefined returns true

+true returns 1

3
xanobius On

I don't think you can break this up like you did, since javascript has his own rules, pretty much like every logical system the first thing fired, i think, will be {}. That creates a neutral object. In the next step [0] should happen, so it takes the first "element" of the object, wich than possibli will be handled as emtpy array. This will be typecasted to False, and that you invert with the "!". Since + expects an integer and true is Not a Number, it will be handled as zero, and in this case incremented by the "+", so the final result is 1.