Search code examples
javascriptjavascript-objects

JS objects: Why can you change a property by setting variable equal to object, but not by setting it equal to object's property?


I have the following JS code:

let a = {
    a1: 1,
    a2: 1,
    a3: 1
}
let b = a
b.a3 = 2
console.log(a) // { a1: 1, a2: 1, a3: 2 }

let d = a.a3
d = 3
console.log(a) // { a1: 1, a2: 1, a3: 2 }

With the first console.log, I've set b to a, changed a property on b, and seen that it is reflected in a.

With the second console.log, I've set d to a property a3 of a, changed d, and seen that it is not reflected in a.

Why the difference?


Solution

  • What's going on here is when you set b to a, it is using b as a reference to a because a is an object. When you set d to a.a3, you are setting d to the value of a.a3 because a.a3 references a value and not the object itself.