Adding two empty arrays:
[] + []
results in an empty string. Why?
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.
Now we can check if the array is empty by using .length . This will return 0, as there are 0 items in the array.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With