Object.assign()
Object.assign() in Modern JavaScript
Object.assign() copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. Prior to the ES2018 object spread operator, Object.assign() was the primary mechanism for object cloning and merging.
1. Syntax and Core Mechanics
target: The target object to receive properties. This object is mutated in-place!...sources: One or more source objects containing properties to copy.- Return Value: The mutated target object.
2. Non-Mutating Cloning & Merging
To avoid mutating existing objects, always pass an empty object {} as the first argument (target):
3. Precedence and Overwriting Order
Properties are copied from left to right. Later sources overwrite earlier sources if keys collide:
4. Object.assign() vs. Object Spread Operator ({ ...obj })
Both achieve shallow cloning and property merging, but there are important nuances:
| Feature | Object.assign(target, source) | Object Spread { ...source } |
|---|---|---|
| In-place Mutation | Can mutate target directly (Object.assign(existing, source)) | Always creates a brand-new object |
| Setters Triggered | Invokes setters on the target object | Does not trigger setters on target (defines own properties) |
| Readability | Functional method call | Compact, idiomatic modern syntax |
| Prototypes | Does not copy prototype chain | Does not copy prototype chain |
5. Important Limitation: Shallow Copying Only
Like the spread operator, Object.assign() does not perform deep copies:
Practice Quiz
Spread in Objects
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Object.keys, Object.values, Object.entries | Spread in Objects |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.