Object.assign
Copies properties from some objects into another.
Available since: ES2015
Syntax
Object.assign(target, ...sources)Parameters
| Parameter | Type | Description |
|---|---|---|
| target | object | The object the properties are copied into. It is changed. |
| ...sources | object | The objects to copy properties from. |
Return value
objectThe same target object.
Examples
Merging settings: later values win:
const defaults = { theme: 'light', size: 14 };
const user = { size: 16 };
console.log(Object.assign({}, defaults, user));Output:
{
"theme": "light",
"size": 16
}The same with spread — more common today:
const defaults = { theme: 'light', size: 14 };
const user = { size: 16 };
const settings = { ...defaults, ...user };
console.log(settings.theme, settings.size);Output:
light 16Notes
The copy is shallow: nested objects are not copied, only their references. For a deep copy use structuredClone().
Pass an empty object {} as the first argument if the source objects must not change.
See also
- Spread syntax — Three dots spread an array or object into separate items.
- structuredClone — Creates a deep copy of an object with all nested data.
- Object.freeze — Prevents any changes to an object.
Related recipes
In the tutorial
- Iterating objects and Object functions — How to iterate over an object in JavaScript: Object.keys, Object.values, Object.entries, Object.fromEntries, for...in and Object.hasOwn.