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

126
Vistas
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 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