Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

70
Visualizações
Spread syntax in an array of objects

I have a question regarding the spread syntax and an array of objects.

Having an array of objects like:

const array = [{age:50}, {age:27}]

According to this answer: https://stackoverflow.com/a/54138394/6781511, using the spread syntax will result in referencedArray having a shallow copy of array.

const referencedArray = [...array]

What then is the difference between using the spread syntax and not using it?

const referencedArray = [...array]

vs

const referencedArray = array
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

See the following example.

When you make a shallow copy, assigning to an element of the original doesn't affect the clone. When you don't make a copy, assigning to the original affects the other reference.

Since it's a shallow copy, assigning to properties of the objects in the array affects all of them. Only the array was copied by spreading, not the objects.

const array = [{age:50}, {age:27}];
const clonedArray = [...array];
const notClonedArray = array;

array[0] = {age: 100};
array[1].age = 30;
console.log("Original:", array);
console.log("Cloned:", clonedArray);
console.log("Not cloned:", notClonedArray);

about 4 years ago · Juan Pablo Isaza Relatório

0

The objects within the arrays have the same reference in both, but in the spread scenario, modifying the array will not affect the original.

const array = [{ name: 'Joe' }, { name: 'Paul' }];
const spreadArray = [...array];
const cloneArray = array;

spreadArray[3] = { name: 'Bob' };
console.log(array); //  [{ name: 'Joe' }, { name: 'Paul' }];

cloneArray[3] = { name: 'Bob' };
console.log(array); //  [{ name: 'Joe' }, { name: 'Paul' }, { name: 'Bob'} ];

That's because cloneArray is assigned by reference to array, while spreadArray is assigned to a new array with the same elements as array. That's also why

cloneArray === array; // true
spreadArray === array; // false
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda