1

My understanding is that:

For [] + [] and [] + {}, the + operator is interpreted as string concatenation, values coerced to strings, so the expressions evaluate to "" and "[object Object]".

For {} + {}, different browser engines interpret it as either string concatenation or addition, so the results vary ("[object Object][object Object]" in Chrome or NaN in Firefox).

Why does {} + [] evaluate to 0?

My line of thinking is that + is interpreted as addition, so {} should be coerced to NaN and [] to 0. Then why doesn't the above expression evaluate to NaN + 0 i.e. NaN?

Vedran Maric
  • 855
  • 9
  • 21
  • Also https://stackoverflow.com/questions/7202157/why-does-return-the-string-10?rq=1 – gman Oct 24 '19 at 16:52
  • 1
    `{}` is an empty code block, so the *actual* expression being evaluated is `+ []` or unary plus followed by an empty array. This will transform the empty array to a number and that number is zero. – VLAZ Oct 24 '19 at 16:52
  • 1
    "*For `{} + {}`, different browser engines interpret it as either string concatenation or addition, so the results vary ("`[object Object][object Object]`" in Chrome or `NaN` in Firefox).*" actually, this is not very correct. Different browser engines will evaluate it *exactly* the same. It's the same logic `{}` is an empty code block then you have `+ {}` which will convert an object to a number and that's `NaN`. However, the Chrome console [cheats](https://stackoverflow.com/questions/36438034/why-is-no-longer-nan-in-chrome-console) and evaluates `({} + {})` – VLAZ Oct 24 '19 at 16:59
  • 1
    which will *change* how this is parsed. You will get exactly the same result if you manually do `({} + {})` in the FF console. With the round brackets, this is *now* evaluated as two objects being joined by `+`. Note that in an actual file `{}` at the start of the line is *still* treated as an empty block, so `{} + {}` will produce `NaN` (and throw it away). – VLAZ Oct 24 '19 at 16:59
  • Very helpful, thank you! – Vedran Maric Oct 24 '19 at 17:08

0 Answers0