-3

I know about the spread operator ... in JavaScript. We can use it on both arrays and objects:

let user = {
  name: "aman",
  rollno: 11
}

let newobj1 = {...user}
let newobj2 = [...user]
console.log(newobj1)
console.log(newobj2)

Why does newobj2 give an error, TypeError: user is not iterable, but newobj1 works fine?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

2

{...user} just creates a new object with the same properties as user.

[...user], on the other hand, iterates through the object and adds the values it finds into the array it returns. If there is no way to iterate, as there isn't by default on a plain object (as opposed to an array), then this doesn't work and raises the error you've quoted.

As always, there is much more information about this on MDN. Note in particular the following section:

Spread syntax (other than in the case of spread properties) can only be applied to iterable objects like Array, or with iterating functions such as map(), reduce(), and assign().

Many objects are not iterable, including Object:

let obj = {'key1': 'value1'};
let array = [...obj]; // TypeError: obj is not iterable

To use spread syntax with these objects, you will need to provide an iterator function.

And note that the "spread syntax" being referred to here is the "array spread" version. "Object spread" is rather different and explained on this part of the page,

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
  • Thanks. This helped me understand the difference between the use of spread operators w.r.t. objects and array. if x is an array then let y = [...x] is also valid and let y = {...x} is also valid but if x is an object then let y = {...x} is valid yet y = [...x] is invalid – Abhinav Srivastava Jun 01 '22 at 01:08
0

{...user}

means that you create new object and spread all the data from user inside it.

When you suppose to execute

[...user]

you tries to create brand new array and then spread the user object inside.

Jaood_xD
  • 808
  • 2
  • 4
  • 16