Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How are reference to objects handled in javascript when returning object and modifying them in their original functions

I am trying to create a function that returns an object and a function that reset this object to its initial state. Something like:

const create = () => ({
    a: "something"
});

const setup = () => {
    let obj = create();

    const reset = () => {
        obj = create();
    }

    return {
        obj,
        reset
    }
}

const { reset, obj: myObj } = setup();

myObj.b = 2;
reset();
console.log("expected to be undefined", myObj.b);

But when I call the function and uses the reset function, it doesn’t reset the object. myObj.2 still contains 2. I expected the reference to myObj to stay the same, so when we call reset obj becomes a new object and myObj’s reference points to that new object.

After some fiddling around I realized that my function works if I do this instead:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const create = () => ({
    a: "something"
});

const setupWithGet = () => {
    let obj = create();

    const getObj = () => obj;

    const reset = () => {
        obj = create();
    }

    return {
        getObj,
        reset
    }
}

const { reset, getObj } = setupWithGet();

getObj().b = 2;
reset();
console.log("expected to be undefined", getObj().b);

Why do I need to use a new function here?

>Solution :

The object returned by setup() contains a reference to the original value of obj. When you reassign obj it doesn’t change this reference, it still refers to the original object. It’s not linked to the variable in any way.

You don’t need any of the methods or scope issues to demonstrate this. See the simple code here:

let obj = {a: "something"};
let container = {obj};
console.log(container);
obj = {a: "something else"};
console.log(container);

Reassigning obj has no effect on the container object. Its reference is to the original value of obj.

In your second version, getObj is a closure that references the local variable obj, not the object. Reassigning the variable updates the variable in that scope, and the function returns that new value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading