1

I want to set object a equal to object b and then edit property x from object a. But, when I edit a.x, b.x gets changed too for some reason. How do I work around this?

var b = {
    x: 0,
    y: 3

};
var a = b;
alert(b.x); //outputs 0
a.x = 1;
alert(b.x); //outputs 1?
dummie40
  • 23
  • 2

1 Answers1

1

Actually, b is pointing to the same object a, i.e, both variables are referencing the same object created initially. Instead, copy all properties to a new object using Object.assign method.

var b = {
  x: 0,
  y: 3

};
var a = Object.assign({}, b);
alert(b.x); //outputs 0
a.x = 1;
alert(b.x); //outputs 1?

For older browser check polyfill option of the method.


Refer :Is JavaScript a pass-by-reference or pass-by-value language?
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188