The Object.assign() method copies all the enumerable properties of the given objects to a single object and returns it.
Example
assign() Syntax
The syntax of the assign() method is:
Object.assign(target, ...sources)
Here, assign() is a static method. Hence, we need to access the method using the class name, Object.
assign() Parameters
The assign() method takes in:
- target - the target object to which we will copy all the properties of the sources.
- sources - the source object(s) whose properties we want to copy.
assign() Return Value
The assign() method returns the target object.
Note: Properties in the target object are overwritten by properties in the sources if they have the same key.
Example 1: Javascript Object.assign() to Clone Objects
In the above example, we have used the assign() method to assign the contents of obj to newObject.
Since assign() modifies the target object and returns the same object, both copy and newObject are clones of one another. As a result, we get identical outputs when we print them both.
Example 2: assign() to Merge Objects
In the above example, we have used assign() to merge the objects o1, o2, and o3 into a new object o4.
const o4 = Object.assign({}, o1, o2, o3);
Using the empty object {} as a target object ensures that the properties of the other objects are copied to a new object without modifying any of the source objects.
As can be seen from the output, properties of later objects overwrite that of earlier ones. For example,
- the
bkey from o1 is overwritten by its counterpart in o2. - the
ckeys from o1 and o2 are overwritten by their counterpart in o3.
Note: If the source value is a reference to an object, it only copies the reference value.
Recommended Reading: