I was working on a problem for flattening arrays. I came across something really strange and can't seem to find an answer online about it.
Why does
[] + [1,2] = '1,2'
I can't seem to wrap my head around why adding an empty array to a populated one results in a string with the contents of the populated array.
What is happening behind the scenes that causes this?
Example from my code:
arr = [1, [2], [3, 4]];
arr.reduce(flatten, []); // [1, 2, 3, 4]
function flatten(a, b) {
return a.concat(b);
}
As far as I understand, reduce will set '[]' as the 'initial value' and thus for each element in the original array it will concatenate it with an empty array thus "flattening" the array.