Output of the code:
const arr = [1, 2, 3, 4, 5];
console.log([...arr + []]);
gives
[ '1', ',', '2', ',', '3', ',', '4', ',', '5' ]
I know ...arr
would return array items (like 1 2 3 4 5) and number + []
gives string, but I really got confused on why ,
is been added to the output array.
Is it because the ...arr
in console.log()
turns out to be [..."1, 2, 3, 4, 5" + []]
in which the output is the same?
Or is the some magical explanation that I am unaware of?
Here is an explanation on +
operator applied to arrays. So what happens is this:
arr + []
gives you a string "1,2,3,4,5"