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.
target: The target object to receive properties. This object is mutated in-place!...sources: One or more source objects containing properties to copy.To avoid mutating existing objects, always pass an empty object {} as the first argument (target):
Properties are copied from left to right. Later sources overwrite earlier sources if keys collide:
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 |
Like the spread operator, Object.assign() does not perform deep copies:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Object.keys, Object.values, Object.entries | Spread in Objects |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.