So i was trying to do this:
var obj1 = {test:0};
var obj2 = obj1;
obj2.test= 2;
console.log(obj1,obj2);
and I expected to return
{test:0} {test:2}
but returned this
{test:2} {test:2}
Is this a bug or this is how object behaves?
So i was trying to do this:
var obj1 = {test:0};
var obj2 = obj1;
obj2.test= 2;
console.log(obj1,obj2);
and I expected to return
{test:0} {test:2}
but returned this
{test:2} {test:2}
Is this a bug or this is how object behaves?
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.
var obj1 = {
test: 0
};
var obj2 = Object.assign({}, obj1);
obj2.test = 2;
console.log(obj1, obj2);
Objects are assigned by reference so if you need to make a copy use Object.assign()
e.g.
var obj1 = {test:0};
var obj2 = Object.assign({}, obj1);
obj1.test = 1;
console.log(obj2.test);
// Using ES6
let object1 = { test: 0 };
let object2 = { ...object1 }
object1.test = 2;
console.log(object2.test);