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.