0

Why is []+[] (two arrays) equal to an empty string in javascript? Furthermore, why does []+{} (array plus an object) equal an object and {}+[]=0?

ars92
  • 1
  • 1
    [wat](https://www.destroyallsoftware.com/talks/wat) – Patrick Roberts Sep 12 '17 at 04:25
  • 3
    `[] + {}` is not an object, and `{} + []` is not zero. If you type it in a REPL, `{}` might be interpreted as an empty block, but it is impossible to encounter this in an actual script. `{} + []` and `[] + {}` both have the same result; both convert `[]` to an empty string and `{}` to `'[object Object]'`, and concatenate the two. `[]` is converted to an empty string in `[] + []` as well. This, in turn, is because `array.toString() === array.join(',')` for any array. – Ry- Sep 12 '17 at 04:29
  • Essentially, “wat” doesn’t say anything useful about JavaScript. It’s just average comedy. – Ry- Sep 12 '17 at 04:31
  • @Ryan: `[] + {}` and `{} + []` are different. Only in the second case `{}` will be interpreted as a block. In the first it's an object literal. Otherwise I agree :) – Felix Kling Sep 12 '17 at 04:34
  • @FelixKling: The expressions `[] + {}` and `{} + []` have the same result. `{} + []` in a given REPL may or may not be an expression. Again, in an actual script, you can’t observe the result of block `{}`, statement `+[]` except in contrived `eval` situations. – Ry- Sep 12 '17 at 04:35
  • @Ryan: In a REPL. But not in an actual program. A leading `{}` will always be interpreted as a block. The spec says so: [Expression statements cannot start with `{`](https://www.ecma-international.org/ecma-262/8.0/#sec-expression-statement). *"you can’t observe the result of block `{}`, statement `+[]`"* That's right, but that doesn't mean that it's not happening ;) – Felix Kling Sep 12 '17 at 04:37
  • @Ryan I'd stipulate that `[] + {}` and `({} + [])` have the same result, since in that case you're coercing the operation into an expression rather than a statement, otherwise saying they're the same is as Felix points out. – Patrick Roberts Sep 12 '17 at 04:38
  • @PatrickRoberts: I said exactly what I meant to say. You’re never going to put `{} + []` in a script and get zero. – Ry- Sep 12 '17 at 04:39

0 Answers0