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

99
Visualizações
object mutation is not expected from return function

Could someone pelase explain the mutation behaviour below:

function test () {
  let data = {}

  const run  = () => {
    console.log(data)
  }

  const update = () => {
    data = {}
  }

  return {
    container: {
      data
    },
    run,
    update
  };
}

const { container, run, update } = test();

update(); // run an update to reset value to {}

container.data.test = { result: 'test' }; // try to mutate the data

run(); // it will still return {} instead { data: {test: {result: 'test'}} }

I would expect to update the object would result mutate the data object inside the function., but looks like it's not the case, as if it created a new object.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const { container, run, update } = test();

This creates a new object which includes the current value of the data variable and assigns it.

update(); // run an update to reset value to {}

This changes the value of the data variable to a new object.

container.data.test = { result: 'test' }; // try to mutate the data

This mutates the object that was originally assigned to data and copied to the new object which was returned from test().

It has no effect on the new object that is now the value of data.


In other words:

  return {
    container: {
      data
    },
    run,
    update
  };

… copies the value of data and does not create a reference to the data variable.

about 4 years ago · Juan Pablo Isaza Relatório

0

When you call the test() function, container.data and data point to the same object:

container.data -----> {} <------ data

but after the following statement:

container.data.test = { result: 'test' };

container.data points to a different object:

container.data -----> { result: 'test' } 
data           -----> {}

but data still points to the empty object and this data variable is logged by the run() function.

Important thing to know here is that re-assigning to container.data doesn't re-assigns to the data variable as well.

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