14

Adding two empty arrays:

[] + []

results in an empty string. Why?

6
  • There's a screencast from a recent conference session that explores odd behaviors of Ruby and Javascript, but as I understand it the Javascript idiosyncrasies are implementation-specific. Commented Feb 15, 2012 at 20:39
  • 5
    I once wrote this part of a larger answer here. Commented Feb 15, 2012 at 20:40
  • @BrianDriscoll that's actually why I am asking the question. Commented Feb 15, 2012 at 20:41
  • @BrianDriscoll: I'm assuming you mean wat. Commented Feb 15, 2012 at 20:42
  • 1
    To add two arrays together, use concat(). array1.concat(array2) Commented Feb 15, 2012 at 20:43

5 Answers 5

27

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.