0

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?

Pramesh Bajracharya
  • 2,153
  • 3
  • 28
  • 54
  • 1
    because `arr + [] === "1,2,3,4,5"` (and there's no destructuring here) – CertainPerformance Dec 21 '18 at 08:05
  • @CertainPerformance what you mean is - there's no `array destructuring` here. – Pramesh Bajracharya Dec 21 '18 at 08:42
  • There's no destructuring at all (array or otherwise) – CertainPerformance Dec 21 '18 at 12:29
  • Oh, thanks for clearing that out. – Pramesh Bajracharya Dec 21 '18 at 17:28
  • *"I know `...arr`would return array items"* It does not. `...` is not an operator, it doesn't do anything. `...arr` by itself would be as invalid as `:arr` would be. `...` is part of the array literal syntax (and function definition/call syntax, and destruturing syntax) and has different meaning depending on where it is used. Just like `;` means something different inside a `for` loop header and at the end of a statement. See https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508 – Felix Kling Dec 21 '18 at 21:06

3 Answers3

2

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.
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
1

Adding on Nurbol's answer when you do

const arr = [1, 2, 3, 4, 5];
console.log([...arr + []]);

It will turn out to a string with each element inside the array converting it to a string. Since the comma is also here so it will be an element of the string array.

When you do it like this

const arr = [1, 2, 3, 4, 5];
console.log((arr + []).split())

It creates the single string of that array and then you create an array of a string specifying the split point.

Harish Soni
  • 1,796
  • 12
  • 27
0

array.toString() adds , after each element

const a = [1, 2, 3, 4, 5]
console.log(a.toString())
// -> '1,2,3,4,5'
console.log([...a.toString()])
// -> [ '1', ',', '2', ',', '3', ',', '4', ',', '5' ]

[...aray + []] converts array to string then adds empty string and then uses [...resultString] to build result

punksta
  • 2,738
  • 3
  • 23
  • 41