n_x_l
n_x_l

Reputation: 1610

Why is the result of adding two empty arrays in JavaScript a string?

Adding two empty arrays:

[] + []

results in an empty string. Why?

Upvotes: 14

Views: 3088

Answers (5)

Sarfraz
Sarfraz

Reputation: 382831

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.

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227310

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

Upvotes: 27

Danny Fox
Danny Fox

Reputation: 40799

The + operator will try to convert the array to string. Use the concat command, if you want to join two or more arrays.

Upvotes: 0

J. K.
J. K.

Reputation: 8368

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.

Upvotes: 3

Chris Sobolewski
Chris Sobolewski

Reputation: 12955

Speculation, but I'm guessing that JavaScript is attempting concatenation there, rather than additon.

Upvotes: 0

Related Questions