Lately i have been experimenting with node.js and I found out that javascript has some syntactic logic that I could not wrap my head around. This is an example I do not understand and I was wondering whether this is just a random javascript fact or if there is any logic to it.
2 Answers
The plus sign is either arithmetic plus or string concatenation. The empty arrays are converted to empty strings in the case of [] + []
.
The Array's toString
method will return one string that is the comma separated list of all of the array's elements.
From the the MDN reference above:
JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
The same idea of automatic type conversion is why true + true === 2
, and type conversion is the basis of many tricky JavaScript quizzes like this one.

- 1
- 1

- 56,972
- 13
- 121
- 140
-
3+1 for essentially the correct answer. Properly speaking, the arrays are _converted_ to strings (via a call to `toPrimitive()`), not cast. See the [EcmaScript spec](http://es5.github.io/#x11.6.1) – Ted Hopp Jul 21 '13 at 17:42
-
@TedHopp - Thanks for the catch. Expanded the answer a little. – Peter Ajtai Jul 22 '13 at 18:52
For Non primitive types like arrays, for applying addition, it has to be converted to primitive, ToPrimitive, would call toString() for non primitive types. So, in this case [] becomes "", and hence "", as the result.

- 990
- 5
- 12