0

Consider the following code:

 A={
  prop1: 12,
  prop2: {x:12}
 };
 newprop2={k:55,l:3};
 A.prop2=newprop2;
 newprop2 = {m:65, n:25};
 console.log(A);

Output is:

  { prop1: 12, prop2: { k: 55, l: 3 } }

I expected the output to be:

  { prop1: 12, prop2: {m:65, n:25} }

Because objects are copied by reference, I was hoping that sub-properties were copied by reference because the objects I want to assign as values are LARGE and do not want to maintain multiple copies.

2 Answers 2

4

Yes, objects are copied by reference. But at the line newprop2 = {m:65, n:25}; you are assigning a new object to the newprop2. The older reference is still assigned to the A.prop2 and it refers to the old object to which newprop2 was referring. So newprop2 now refers to another object which is already has nothing with the object to which it was refering before.

In concise, you have changed the reference of the newprop2. If you will access properties via newprop2, not change the reference, you will mutate the same object to which A.prop2 refers.

const A = {
  prop1: 12,
  prop2: { x: 12 }
};

let newprop2 = { k:55, l:3 };
A.prop2 = newprop2;

newprop2.k = 65;
newprop2.l = 25;

console.log(A);

Sign up to request clarification or add additional context in comments.

Comments

0

Yes because it was referenced by newprop2={k:55,l:3}; . later on you had changed reference of newprop2 but it was after assignment was done , so prop2 of A has older refrence of newprop2 . at the end A.prop2 !== newprop2 .you have to set value to property prop2 once you assigned new value to newprop2. So just assign prop2 values after new assignment of prop2.

 A={
  prop1: 12,
  prop2: {x:12}
 };
 newprop2={k:55,l:3};
 newprop2 = {m:65, n:25};
  A.prop2=newprop2;
 console.log(A);

Now A.prop2 === newprop2 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.