Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!