Languages

JavaScript - modifying object copy causes the original object change

0 points
Asked by:
JoanneSenior
1070

Why is modifying copy of an object causing the original object change?

My code:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

You've misunderstood the statement: var object2 = object1.

In JavaScript, objects are passed and assigned by reference, so object1 and object2 are references pointing to the same object.

 

Solution

To avoid it, you can create a copy of the object:

Full example:

 

See also

  1. JavaScript - clone object

References

  1. Object.assign() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join