Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
Difference between [...obj] and {...obj}

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

{...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,

about 4 years ago · Juan Pablo Isaza Denunciar

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda