4

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?

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • related: *Why is ++[[]][+[]]+[+[]] = “10”* http://stackoverflow.com/q/7202157/205233 – Filburt Jun 23 '15 at 16:40
  • 2
    Even though I don't think these kind of questions are really valuable for Stack Overflow, I'm glad you spent some time to figure it out on your own. – Felix Kling Jun 23 '15 at 16:44

2 Answers2

9

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

{}[0] returns undefined

!undefined returns true

+true returns 1

basilikum
  • 10,378
  • 5
  • 45
  • 58
  • @basilikum While i check on console (chrome or FF) for `{}[0]` returns `[0]` instead of `undefined`. Why? . Also what does it mean in favor of `![0]`. – Raj Jun 27 '15 at 08:09
  • @RJ this must be special behavior of the console. I cannot tell you why it happens in chrome, but if you write `var a = {}[0];` and then just log `a`, it shows the correct value (`undefined`). So my guess is that in this case, Chrome sees `{}` and `[0]` as two independent statements and just prints the result of the second one. The same happens, if you write `{}"hello"`, which will print `hello`. But in any way, `{}[0]` definitely is `undefined`. – basilikum Jun 27 '15 at 10:49
  • @basilikum Thanks! you're right. By your way it shows `undefined` now. – Raj Jun 27 '15 at 10:54
0

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.

xanobius
  • 148
  • 7
  • I know, it just caught me off-guard. – Richard Hamilton Jun 23 '15 at 16:45
  • *"so it takes the first "element" of the object, wich than possibli will be handled as emtpy array."* No. This just tries to read the property `0` from the object. It has nothing to do with arrays. – Felix Kling Jun 23 '15 at 16:48
  • Of course, you're right. Either way, since there is no property 0 it will be converted to false (since undefined as boolean in js is regarded as false). – xanobius Jun 23 '15 at 16:58