Updating copied object also updates the parent object in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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' }
raja
Updated on 10-Sep-2020 07:30:11

Advertisements