Copy objects with Object.assign() in JavaScript


The Object.assign() method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target.

The syntax is as follows −

Object.assign(target, ...source objects);

Following is the code to copy object −

Example

var object = {first: second => second + 1000}
var object2= Object.assign({}, object);
console.log("The result=");
console.log(object2.first(1000));

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

node fileName.js.

Here, my file name is demo102.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo102.js
The result=
2000

Updated on: 07-Sep-2020

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements