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.
Adding empty arrays results in a string.
In other terms, [] + []
returns ""
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:
[1] + [] //returns "1"
[1] + [2] //returns "12"
[1,2,3] + [2] //returns "1,2,32"
[{foo:'bar'},'foo','bar'] + [] //returns "[object Object],foo,bar"
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.
'foo' + {foo:'bar'} //returns "foo[object Object]"
1 + {foo:'bar'} //returns "1[object Object]"
{foo:'bar'} + 1 //returns 1
{foo:'bar'} + 'foo' //returns NaN
This happens unless I assign the object to a variable. If I use X = {foo:'bar'}
,
X + 'foo' //returns "[object Object]foo"
And the object is back to turning into a string.
I can understand why this sort of casting might happen in a ==
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?