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?
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?
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.
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
.