0

I am a little confused, by what might be a simple topic. I first encountered this today and was a little startled. Suppose you have the following code

let x = {a: 100}
let y = {b: x} //Note the x value

Now the interesting part is when you update x

x.a = 200

console.log(x)
console.log(y)

> { a: 200 }
> { b: { a: 200 } }

It gets updated in both objects. I was under the impression that y would create a brand new object despite using a reference to x. Now my mind is blown by this fact. What is going on here? What is the topic being illuminated here?

me_man
  • 97
  • 1
  • 7

1 Answers1

0

In your case that just makes a shallow copy of the same object. In order to create a new Object(deep copy) use Object.assign

let x = {
  a: 100
}
let y = {
  b: Object.assign({}, x)
}

x.a = 200;

console.log(x)
console.log(y)
brk
  • 48,835
  • 10
  • 56
  • 78