Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Adding two empty arrays:

[] + []

results in an empty string. Why?

like image 853
n_x_l Avatar asked Feb 15 '12 20:02

n_x_l


People also ask

What happens if we add two arrays in JavaScript?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

What does an empty array return JavaScript?

Now we can check if the array is empty by using .length . This will return 0, as there are 0 items in the array.

What does an empty string mean in JavaScript?

The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.


2 Answers

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

like image 86
Rocket Hazmat Avatar answered Nov 15 '22 14:11

Rocket Hazmat


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.

like image 21
J. K. Avatar answered Nov 15 '22 13:11

J. K.