Skip to content
Advertisement

exporting deep copy of object in javascript

const obj = {A: 2};
module.exports = JSON.parse(JSON.stringify(obj));

Will every module that imports from the above module receive a different copy? Or will they all receive the same copy?

Advertisement

Answer

Short answer: No. It will return the same instance for every one.

Long answer:

I suggest you read about how the module system works in JavaScript/Node.

A good mental model is that when a module is imported for the first time and runs all of the code within in order to set the exported variables to what they should be before returning them.

The next time it is imported, it will return the exported variables which have already been set. It will not run the module source again for every time you import it.

If you need to have a different object for every import, you will need to generate one by exporting a function instead of a value:

const obj = {A: 2};
module.exports = () => JSON.parse(JSON.stringify(obj));

…later

const uniqueObj = require("./mymodule")(); // call function
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement