1

In the below code, how is objA.foo value is set to 'bar'? (No-vice Javascript developer). Which concept or functionality in JS sets the value of objA property to 'bar'?

var objA = Object.create({
    foo: 'foo'
});
var objB = objA;
objB.foo = 'bar';
console.log(objA.foo);
console.log(objB.foo);
gaurav
  • 21
  • 1
  • 10
  • 2
    Simply the fact that `var objB = objA;` doesn’t create a copy of the object. See [Javascript's assignment operation is to copy references?](https://stackoverflow.com/q/8792401/4642212). – Sebastian Simon Aug 20 '18 at 22:03

2 Answers2

2

var objB = objA does not create a copy of the object. It holds a reference to objA. Modifying the object through the reference changes it for both variables holding a reference to that object.

To clone the Object, you can use JSON.parse(JSON.stringify(obj)).

var objA = Object.create({
    foo: 'foo'
});
var objB = JSON.parse(JSON.stringify(objA));
objB.foo = 'bar';
console.log(objA.foo);
console.log(objB.foo);

You can also use Object.assign({}, obj).

var objA = Object.create({
    foo: 'foo'
});
var objB = Object.assign({}, objA);
objB.foo = 'bar';
console.log(objA.foo);
console.log(objB.foo);

See the documentation.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

var objB = objA;

You're actually creating a reference to objA. If you'd like to copy the object without a reference you can use the spread syntax:

var objB = {...objA};

Also, see: How do I correctly clone a JavaScript object?

wdm
  • 7,121
  • 1
  • 27
  • 29
  • @Xufox https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Specifications – wdm Aug 20 '18 at 22:16
  • Yes, what about this specification table? Spread syntax has been around since ES6 for _arrays, arguments and parameters_, not for objects. [_Object_ spread](http://kangax.github.io/compat-table/es2016plus/#test-object_rest/spread_properties) has only been specified in ES 2018, which is ES9. – Sebastian Simon Aug 20 '18 at 22:19
  • You're correct the MDN doc is missing the explicit reference to the addition of object spread in ES9 in their table. I'll forward your concerns to them. – wdm Aug 20 '18 at 22:29