-2

I was doing the following:

let obj = {
    a: 'Hi',
}

let copy = obj;
copy.a = 3;

console.log(obj.a);

To my surprise, the value of obj.a is also 3. Does anybody know why this is happening and how to fix it?

Sheldore
  • 37,862
  • 7
  • 57
  • 71
Tom Oconnor
  • 393
  • 2
  • 5
  • 14
  • 1
    Possible duplicate of [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Maximilian Burszley Aug 20 '18 at 22:40
  • 1
    Assignment of object references does not create a copy. That's how the language works; it's fundamental. – Pointy Aug 20 '18 at 22:43
  • Possible duplicate of [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change) – Sebastian Simon Aug 20 '18 at 22:44
  • Possible duplicate of [How to copy JavaScript object to new variable NOT by reference?](https://stackoverflow.com/questions/18359093/how-to-copy-javascript-object-to-new-variable-not-by-reference) – Obsidian Age Aug 20 '18 at 22:47

2 Answers2

1

Primitive types are passed as value, like Booelan, String, Numbers.

Object types are passed as reference like Array, Function, and Object

You can use Object.assign(), in the docs it states: The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

let obj = {
    a: 'Hi',
}

let copy = Object.assign({},obj);
copy.a = 3;

console.log(obj.a);

So in our example {} is our target (an empty object) and our source is the obj variable.

Bergur
  • 3,962
  • 12
  • 20
1

When you assign an Object type to a variable, you're essentially storing what is called a pointer. A pointer is simply an address in the system memory to where the data for the object is stored.

In your example

let obj = { a: 'Hi' } // obj is now pointing to a reference, say, 0x1a, in memory

Now when you do

let copy = obj // copy is now pointing to the same location in memory, that is, 0x1a

In essence copy and obj are not the data in the object, rather they are an address to the object. The object itself, is some data blob that lives at memory location 0x1a. Adding/removing/editing properties on either obj or copy, does nothing other than modify the data that lives at 0x1a.

seebiscuit
  • 4,905
  • 5
  • 31
  • 47