Why is the result of adding two empty arrays in JavaScript a string?
Because the +
operator serializes the two arrays and concatenates the two results. The serialization is done via the Array.prototype.toString
method which basically does this:
function () { return this.join(','); }
The two arrays are empty, thus the string returned by toString
is also empty and two empty strings make an empty string as well.
In JavaScript, there are two types of value: primitives which include null
, undefined
, boolean
, string
and number
; everything else is an object
, including array
When adding things, JavaScript converts values to numbers, strings or primitives. Internally, JavaScript uses the toPrimitive
method to convert variables to primitive.
Here is the signature of toPrimitive
:
toPrimitive(input, preferedType);
With [] + []
, JavaScript converts []
to a primitive, first tries valueOf()
which returns the array:
var arr = [];
arr.valueOf() === arr // true
As that result is not a primitive, toString()
is called and returns the empty string (string is a primitive). Therefore, the result of [] + []
is the concatenation of two empty strings.
The +
operator only exists for numbers and strings. When you use it on another type, JavaScript tries to convert the type (first to string, then int).
When arrays are casts to strings, they are output as comma-separated strings.
So, [] + []
=> "" + ""
=> ""
.
Another example: [1,2] + [3,4]
=> "1,2" + "3,4"
=> "1,23,4"
Relevant Spec: https://tc39.es/ecma262/#sec-addition-operator-plus