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

130
Visualizações
Javascript Object attribute updated by nested block is lost?

I would like to understand about this particular behaviour of Javascript. I have an object defined in the parent scope.

In a nested scope, I created a variable which references a particular object attribute (an array) of my object. Using this variable (a reference) I updated the attribute of the object. But post the nested block, I find that my update was lost?

I tried to wrap my head around this but I'm stuck.

I would think that the variable inside the nested block myOldRef should be able to access the object defined in the parent block and hence should be able to update it via reference? Also how is the value being "set back" to the older value? Is Javascript creating a copy of the object inside the nested block?

Am I missing something? Would like to know the intricacies of this behaviour.

Here is the code in question.

var a = {
  a: 'Hello',
  b: 'World',
  c: {
    mList: [0,1,2,3]
  }
}

let myRef = a['c']['mList'];
let myOldRef;

console.log(`First time: ${myRef}`);

myRef = [4,5,6,7];

console.log(`After first update: ${myRef}`);

if(true) {
  myOldRef = a['c']['mList'];
  let myNewRef = [3,4,5,6];
  myOldRef = myNewRef;
  console.log(`Inside nested block, After update: ${myOldRef} -- why is this update lost?`);
}


console.log(`Outisde nested block, After update: ${myRef}`);

You can also run the code here on replit if you'd like.

about 4 years ago · Juan Pablo Isaza
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