0

I was experimenting with the spread syntax and am having difficulty making rational sense out of its behavior in a particular situation.

In one instance, when I use:

const art = ["hello"]
console.log( [{...art}] )

the return value is 
=> [ { '0': 'hello' } ]

However, when I iterate over the single array value it produces an entirely different effect:

const art2 = art.map((item) => ({ ...item }))
console.log(art2)
=> [ { '0': 'h', '1': 'e', '2': 'l', '3': 'l', '4': 'o' } ]

Why does using the spread syntax in the first example only combine it with a single index, but in the second example with .map being used break it down into different index elements? Since there is only a single item in the art array I would have assumed the results would be the same.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Dog
  • 2,726
  • 7
  • 29
  • 66

3 Answers3

1

In the first code, you're spreading an array which contains one item, a string at the zeroth index:

console.log({ ...["hello"] });

All is as expected. But in the second code, you're calling .map on the array first, and then spreading the first argument provided to the .map function - the items being spreaded aren't arrays, but the items the array contains, which, in this case, is a string. When you spread a string, you'll get properties matching the values at each character index:

console.log(['hello'].map((item) => ({ ...item })))
// same as:
console.log({ ...'hello' });

They're entirely different situations.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Both results are as expected.

In first case you are passing whole array to spread operator

const art = ["hello"]
console.log( [{...art}] )

So spread operator is applied to whole array at once.

In second case, first you are iterating the array using .map() i.e. you are picking each item and passing that item to spread operator.

const art2 = art.map((item) => ({ ...item }))
console.log(art2)

So spread operator is applied to each item.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
1
                                 const art = ["hello"]

In above case, you tried to spread the array. So it will give you following output :

                                 [ { '0': 'hello' } ]

Now you tried to execute following one

                        const art2 = art.map((item) => ({ ...item }))

So here you have used map. Map is something which takes one element of array and applies mapper to it. In your case your mapper is to spread the given element. So now it will spread the element you have passed. So you got the output as :

                  [ { '0': 'h', '1': 'e', '2': 'l', '3': 'l', '4': 'o' } ]