Why does [] + [] return an empty string?

I have been experimenting with node.js lately, and I found out that javascript has syntax logic with which I could not wrap my head. This is an example that I don't understand, and I was wondering if this is just a random fact of javascript or if there is any logic.

+4
source share
2 answers

The plus sign is either arithmetic or string concatenation. Empty arrays are converted to empty strings in the case of [] + [] .

The Array toString method returns a single line, which is a list of all elements of the array, separated by a comma.

In the above MDN link:

JavaScript calls the toString method automatically when the array should be represented as a text value or when the array refers to string concatenation.

The same idea of ​​automatic type conversion is why true + true === 2 , and type conversion is the basis of many complex JavaScript tests such as this one .

+8
source

For non-primitive types, such as arrays, to apply the addition, it must be converted to primitive, ToPrimitive, call toString () for non-primitive types. Thus, in this case, [] becomes "and therefore" ", as a result.

+3
source

Source: https://habr.com/ru/post/1492592/


All Articles