Categories
JavaScript Answers

How to copy JavaScript object to new variable not by reference?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *