Why does javascript change objects into other things when added?
<p>Something interesting about adding empty arrays in javascript was pointed out to me, and I have no idea why it works the way it does.</p>

<p>Adding empty arrays results in a string.</p>

<p>In other terms, <code>[] + []</code> returns <code>""</code></p>

<p>I booted up my console to test it, and sure enough, it works. I further discovered that this behavior is not limited to empty arrays. Arrays of numbers, strings, arrays, and objects all turn into strings when added to any other array. Some examples are:</p>

<pre><code>[1] + [] //returns "1"
[1] + [2] //returns "12"
[1,2,3] + [2] //returns "1,2,32"
[{foo:'bar'},'foo','bar'] + [] //returns "[object Object],foo,bar"
</code></pre>

<p>It also occurs with other objects, when added to anything else, but only if the object is on the right hand side. If it's on the left hand side, the object is turned into 0.</p>

<pre><code>'foo' + {foo:'bar'} //returns "foo[object Object]"
1 + {foo:'bar'} //returns "1[object Object]"
{foo:'bar'} + 1 //returns 1
{foo:'bar'} + 'foo' //returns NaN
</code></pre>

<p>This happens unless I assign the object to a variable. If I use <code>X = {foo:'bar'}</code>,</p>

<pre><code>X + 'foo' //returns "[object Object]foo"
</code></pre>

<p>And the object is back to turning into a string.</p>

<p>I can understand why this sort of casting might happen in a <code>==</code> operator, but why does addition do this? Why does addition change arrays and objects (and yes, I know that arrays are objects, too) into other things?</p>
