7

Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

Could someone explain to me how thees returning results can be different in javascript:

› {} + []
» 0
› [] + {}
» "[object Object]"
Community
  • 1
  • 1
superhero
  • 6,281
  • 11
  • 59
  • 91

1 Answers1

7

This is because the {} in the code is not an object literal, but an empty block.

It is parsed as:

{};   // empty block
+ []; // this result is shown in the console

Compare with ({}) + [] which yields the same results as [] + {}; in this case the parenthesis force the {} to be treated/parsed "in an expression context".

There are a bunch of duplicates on SO about this particular dual-nature of {} (as an expression or block?) but, finding them can be somewhat tricky ..


I found https://meta.stackexchange.com/questions/83911/how-do-i-search-stackoverflow-for-at-keywords-like-private-or-synthesize on Meta, and using Symbolhound the "closest" duplicates I could find resolved around questions like this (that relate to the need to add parenthesis when "eval'ing JSON") or this (where the use of constructs like "{} == false" is a syntax error).

If anyone knows a better way to search SO for this sort question, or has a link to such a duplicate handy ..

Community
  • 1
  • 1
  • @ErikLandvall If you find some duplicates, just vote to close/link :) Don't delete the question, it will be closed as/if appropriate. –  Aug 17 '12 at 04:51
  • Actually finding the duplicates is the problem. I'm sure I saw the same question within the last couple of days, but searching on `[]` doesn't work too well. – nnnnnn Aug 17 '12 at 05:00
  • Yea, I had that problem to. Now I'm just trying to merge them as pst stated. http://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the – superhero Aug 17 '12 at 05:49