Search code examples
javascriptecmascript-6destructuring

JS Array Destructing - How is it giving this output?


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?


Solution

  • Here is an explanation on + operator applied to arrays. So what happens is this:

    1. arr + [] gives you a string "1,2,3,4,5"
    2. Then that string is spreaded/splitted (with the spread syntax) into an array of characters of that string.