Sometimes, we want to copy JavaScript object to new variable not by reference.
In this article, we’ll look at how to copy JavaScript object to new variable not by reference.
How to copy JavaScript object to new variable not by reference?
To copy JavaScript object to new variable not by reference, we make a copy of the object before we pass it into a function as an argument.
For instance, we write
const copyObj = JSON.parse(JSON.stringify(jsonObj));
to call JSON.stringify with jsonObj and then call JSON.parse on the JSON string to make a deep copy of the object.
And then we assign the returned copied object to copyObj.
Then we can use copyObj as the argument of a function and it doesn’t reference the original jsonObj object.
Conclusion
To copy JavaScript object to new variable not by reference, we make a copy of the object before we pass it into a function as an argument.