How to Use Object.assign in JavaScript: Syntax and Examples
Use
Object.assign(target, ...sources) to copy properties from one or more source objects into a target object. It merges properties from sources into the target, overwriting existing keys if they match.Syntax
The Object.assign method takes a target object and one or more source objects. It copies all enumerable own properties from the source objects to the target object and returns the target.
target: The object to receive new properties.sources: One or more objects whose properties will be copied.
javascript
Object.assign(target, ...sources)Example
This example shows how to merge two objects into one using Object.assign. Properties from the second object overwrite those in the first if keys match.
javascript
const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const returnedTarget = Object.assign(target, source); console.log(target); // Output the modified target console.log(returnedTarget); // Same as target
Output
{ a: 1, b: 4, c: 5 }
{ a: 1, b: 4, c: 5 }
Common Pitfalls
One common mistake is expecting Object.assign to do a deep copy. It only copies properties at the first level, so nested objects are copied by reference, not duplicated.
Also, if the target object is frozen or sealed, Object.assign will fail silently or throw an error in strict mode.
javascript
const target = {}; const source = { nested: { a: 1 } }; const result = Object.assign(target, source); result.nested.a = 2; console.log(source.nested.a); // Shows 2, not 1, because nested object is shared
Output
2
Quick Reference
- Copies properties: from sources to target.
- Returns: the modified target object.
- Shallow copy: nested objects are shared, not cloned.
- Overwrites: properties with the same key.
Key Takeaways
Object.assign copies enumerable own properties from source objects to a target object.
It performs a shallow copy, so nested objects are shared, not duplicated.
The target object is modified and returned by the method.
Properties in later sources overwrite earlier ones if keys match.
Use Object.assign for simple merges, but not for deep cloning.