Syntax error Updating copied object also updates the parent object in JavaScript?

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' }
Updated on: 2020-09-10T07:30:11+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements