0

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?

Facundo Silva
  • 111
  • 1
  • 6
  • 1
    This is how objects behave. Unless you explicitly create a new one, both variables contain references to the same object. – Bergi May 13 '18 at 18:26
  • Objects are **mutable** in javascript. So you need to clone it. there are lot of ways, you can achieve: `JSON.parse(JSON.stringify(obj1))` and `Object.assign` – Avnesh Shakya May 13 '18 at 18:31

2 Answers2

1

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);

source

Saeed
  • 5,413
  • 3
  • 26
  • 40
0

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);
 
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60