JavaScript(JS) object method - assign

The Object.assign() method is a built-in method of the Object object in JavaScript. It is used to copy the values of all enumerable properties from one or more source objects to a target object, and returns the target object.

Here's an example usage:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const result = Object.assign(target, source);

console.log(target); // { a: 1, b: 4, c: 5 }
console.log(result); // { a: 1, b: 4, c: 5 }
Sourc‮e‬:www.theitroad.com

In the above example, the Object.assign() method is called with target as the first argument and source as the second argument. The method copies the values of the b property from the source object to the target object, and adds the c property to the target object. The resulting target object is { a: 1, b: 4, c: 5 }.

Note that the Object.assign() method modifies the target object in place and returns the modified object. If you don't want to modify the original object, you can pass an empty object as the first argument:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const result = Object.assign({}, target, source);

console.log(target); // { a: 1, b: 2 }
console.log(result); // { a: 1, b: 4, c: 5 }

In the above example, the Object.assign() method copies the values of the a and b properties from the target object and the b and c properties from the source object to a new empty object. The resulting object is { a: 1, b: 4, c: 5 }, and the original target object is not modified.