Search code examples
javascriptecmascript-5

Object property-value behavior in Javascript


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

Solution

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