Search code examples
javascriptreferencejavascript-objects

Javascript: Why does the '=' operator in object assignment creates a reference to the already existing object?


I was doing the following:

let obj = {
    a: 'Hi',
}

let copy = obj;
copy.a = 3;

console.log(obj.a);

To my surprise, the value of obj.a is also 3. Does anybody know why this is happening and how to fix it?


Solution

  • Primitive types are passed as value, like Booelan, String, Numbers.

    Object types are passed as reference like Array, Function, and Object

    You can use Object.assign(), in the docs it states: 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.

    let obj = {
        a: 'Hi',
    }
    
    let copy = Object.assign({},obj);
    copy.a = 3;
    
    console.log(obj.a);

    So in our example {} is our target (an empty object) and our source is the obj variable.