0

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?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • 1
    Object (arrays and functions included) are pare passed by reference, other types are passed by value so `b` and `a` hold the same object and `d` is a copy of `a.a3` – Konrad Jan 31 '23 at 18:36

1 Answers1

3

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.

EpicPuppy613
  • 301
  • 1
  • 13