Updating copied object also updates the parent object in JavaScript?



No, the parent object won’t get updated. Use Object.assign() with some parameters and check. Following is the code −

Example

var firstObject = { name: 'John' };
var secondObject = { name: 'Carol' };
console.log("Before merging=");
console.log(firstObject);
var afterMerging = Object.assign({}, firstObject, secondObject);
afterMerging.name = 'Smith';
console.log("After merging=");
console.log(firstObject);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo131.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo131.js
Before merging=
{ name: 'John' }
After merging=
{ name: 'John' }

Advertisements