-3

When I have an object defined as such,

const obj = {
    first: "hey",
    second: "hello"
}

and I do not wish to modify this but create a new object and reassign values to that.

I though doing this should work:

const testObj = obj;
testObj[first] = "heyyy"

However, this causes the original 'obj' object to modify as well. I figured out that using the spread operator will be a solution for this, however, can someone explain why doing testObj = obj, is causing the 'obj' object to be modified every time testObj is modified.

Alexander Nied
  • 11,309
  • 4
  • 26
  • 41
TanDev
  • 239
  • 1
  • 4
  • 11
  • 1
    Because `const testObj = obj;` assigns the reference of the old object to the new variable. Both variables now point to the same object reference. – Andy May 06 '22 at 19:37

0 Answers0