Categories
JavaScript Answers

How to pass object by value with JavaScript?

Spread the love

Sometimes, we want to pass object by value with JavaScript.

In this article, we’ll look at how to pass object by value with JavaScript.

How to pass object by value with JavaScript?

To pass object by value with JavaScript, we make a copy of the object.

For instance, we write

const obj2 = { ...obj1 };
foo(obj2);

to make a shallow copy of obj1 with the spread operator and assign the copied object to obj2.

Then we call foo with obj2 without affecting obj1.

Conclusion

To pass object by value with JavaScript, we make a copy of the object.

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 *