Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
Richard Hamilton Avatar asked Jan 09 '23 02:01

Richard Hamilton


1 Answers

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

{}[0] returns undefined

!undefined returns true

+true returns 1

like image 138
basilikum Avatar answered Jan 10 '23 17:01

basilikum