2

I was recently alarmed to discover the following:

> {}+[]
0

> ({}+[])
"[object Object]"

> {}+[]+1
1

> ({}+[])+1
'[object Object]1'

> {}+[] == ({}+[])
false

Why does wrapping something in parenthesis change its type?

Crashworks
  • 40,496
  • 12
  • 101
  • 170
  • Basically, you're doing weird things in a non-compiled language...so you're invoking strange defaults and behaviors that aren't defined in spec... https://www.destroyallsoftware.com/talks/wat – CaffGeek Apr 04 '16 at 18:20
  • 3
    @CaffGeek This behavior is completely by spec. – Madara's Ghost Apr 04 '16 at 18:21
  • where? (genuinely curious if that's in there) – CaffGeek Apr 04 '16 at 18:22
  • 1
    Of course it's in there. It's just how tokens are regarded by lexical analysis and how they are casted as operands for `+`, nothing uncommon. – bevacqua Apr 04 '16 at 18:23
  • I know this is a duplicate but I can't find a good one. – Pointy Apr 04 '16 at 18:26
  • And for the record `( )` do not change the type of anything. They alter the way the parser interprets tokens in certain ambiguous situations. (Actually it's more like, they alter the *situation* to change how tokens are interpreted.) – Pointy Apr 04 '16 at 18:26
  • Wow, I would have never been able to find that earlier question with the search terms I was using (permutations on "javascript parenthesis type conversion" etc). Also, this business of ({}+[])+1 != {}+[]+1 doesn't show up in the Wat talk. – Crashworks Apr 04 '16 at 18:27
  • Parentheses can also convert function declarations to function expressions: [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/q/1634268/1529630) – Oriol Apr 04 '16 at 18:27
  • 1
    @Crashworks for more laughs try `({}+[])+1 == {}+[]+1` in your browser console. – Pointy Apr 04 '16 at 18:29
  • @Pointy (╯°□°)╯︵ ┻━┻ – Crashworks Apr 04 '16 at 18:45

1 Answers1

5

{} + [] is an empty block followed by a an array with a unary + operator, which is essentially, which is +[] which is 0,

({} + []) is a literal object plus a literal array, both get converted into strings, the string value of an object is "[object Object]" plus the string value of an empty array which is "", hence the result you see.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308