Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Lately i have been experimenting with node.js and I found out that javascript has some syntactic logic that I could not wrap my head around. This is an example I do not understand and I was wondering whether this is just a random javascript fact or if there is any logic to it.

like image 579
Joren Avatar asked Dec 21 '22 02:12

Joren


1 Answers

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

The Array's toString method will return one string that is the comma separated list of all of the array's elements.

From the the MDN reference above:

JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

The same idea of automatic type conversion is why true + true === 2, and type conversion is the basis of many tricky JavaScript quizzes like this one.

like image 89
Peter Ajtai Avatar answered Jan 06 '23 12:01

Peter Ajtai