JavaScript Object.assign(target, ...sources) method
The Object.assign(target, ...sources)
method in JavaScript is used to copy the values of all enumerable properties from one or more source objects to a target object. This method can be particularly useful for merging objects, creating shallow copies, or assigning default values.
Syntax:
Parameters:
target
: The object to which properties will be copied. This object is also returned by the method....sources
: One or more source objects from which properties will be copied. Properties from later sources overwrite properties from earlier ones if they have the same key.
Return Value:
- The modified
target
object.
Key Features:
- Shallow Copy:
Object.assign()
creates a shallow copy of properties. This means that if the source object has nested objects, only the reference to those nested objects is copied, not the nested objects themselves. - Overwriting Properties: If the same property exists in multiple source objects, the value from the last source will overwrite the previous values in the target object.
- Non-Enumerable and Symbol Properties: Only the object's own enumerable properties are copied. Non-enumerable properties and symbol properties are ignored.
Example 1: Basic Usage
In this example, properties from the source
object are copied to the target
object. The target
object is modified and returned.
Example 2: Merging Objects
In this example, an empty object {}
is used as the target. The properties from both obj1
and obj2
are merged into the new object, with obj2
's b
property overwriting obj1
's b
property.
Example 3: Shallow Copying
In this example, modifying copy.a
does not affect obj.a
, but modifying copy.b.c
affects obj.b.c
because both copy.b
and obj.b
reference the same nested object.
Example 4: Overwriting Properties
In this case, the b
property in options
overwrites the b
property in defaults
.
Summary:
Object.assign(target, ...sources)
is a powerful method for copying properties from one or more source objects to a target object.- It is commonly used for merging objects, creating shallow copies, and assigning default values.
- Understanding how
Object.assign()
handles properties is crucial for effective object manipulation in JavaScript, especially when working with complex objects or configurations.