Object.assign() Since: ES6(ECMAScript 2015)
Copies properties from one or more source objects to a target object. Use this method to merge or clone objects.
Syntax
// Copies properties from the source to the target.
Object.assign(target, source)
// You can specify multiple sources.
Object.assign(target, source1, source2, ...)
// Copying and merging objects with spread syntax
var copy = { ...originalObject };
var merged = { ...object1, ...object2 };
Sample Code
// Creates a copy of an object.
var original = { name: "Kuu", age: 25 };
var copy = Object.assign({}, original);
console.log(copy); // Outputs: { name: "Kuu", age: 25 }
// Merges multiple objects together.
var defaults = { color: "red", size: "M" };
var custom = { size: "L", weight: 100 };
var result = Object.assign({}, defaults, custom);
console.log(result); // Outputs: { color: "red", size: "L", weight: 100 }
// If the same key exists, the later object's value overwrites the earlier one.
console.log(result.size); // Outputs: "L"
// You can do the same thing with spread syntax.
var copy2 = { ...original };
console.log(copy2); // Outputs: { name: "Kuu", age: 25 }
var merged = { ...defaults, ...custom };
console.log(merged); // Outputs: { color: "red", size: "L", weight: 100 }
// If you pass an existing object as the target, that object is modified directly.
var target = { a: 1 };
Object.assign(target, { b: 2, c: 3 });
console.log(target); // Outputs: { a: 1, b: 2, c: 3 }
Object.assign() vs Spread Syntax
| Feature | Object.assign() | Spread syntax |
|---|---|---|
| Syntax | Object.assign({}, a, b) | { ...a, ...b } |
| Target mutation | The first argument object is modified directly. | Always creates a new object. |
| Copy depth | Shallow copy only. Nested objects are copied by reference. | Also shallow copy only. |
Overview
Object.assign() is a method that copies the enumerable own properties of one or more source objects into a target object. The first argument is the target, and all subsequent arguments are sources. Multiple objects are merged left to right, so if the same key appears in more than one source, the last value wins.
Note that Object.assign() performs a shallow copy. Nested objects and arrays are copied by reference, so modifying them in the target will also affect the original source. If you need a deep copy, use structuredClone() or JSON.parse(JSON.stringify()).
Since ES2018, copying and merging with spread syntax { ...obj } has become the preferred approach. Because spread syntax always returns a new object, it is easier to avoid unintended mutations.
Browser Compatibility
44 or earlier ×
33 or earlier ×
Android Browser
50+ ○
44 or earlier ×
Chrome Android
50+ ○
44 or earlier ×
Firefox Android
79+ ○
33 or earlier ×If you find any errors or copyright issues, please contact us.