viery365
viery365

Reputation: 965

Why a nested object is not passed by reference?

There are millions of questions about this topic but I cannot find an explanation for this situation:

const obj = { nObj: {a: 1}};

const obj2 = obj.nObj; // the value of obj2 is an object, not a primitive

obj.nObj = {b: 2};

console.log(obj2) // outputs {a: 1}

Why does this happen?

Upvotes: 2

Views: 49

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Please note, values are passed by reference and not the keys

Here is the explanation below in comments.

// There are 2 references here one being referenced by obj and the other is by obj.nObj
const obj = { nObj: {a: 1}};

// obj2 also starts pointing to the same reference as obj.nObj
const obj2 = obj.nObj; // the value of obj2 is an object, not a primitive

// obj.nObj now points to a different reference
obj.nObj = {b: 2};

// obj2 continues to hold the original reference, hence, remains unchanged.
console.log(obj2) // outputs {a: 1}

Upvotes: 3

Related Questions