Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Object.assign

Copies properties from some objects into another.

Available since: ES2015

Syntax

Object.assign(target, ...sources)

Parameters

ParameterTypeDescription
targetobjectThe object the properties are copied into. It is changed.
...sourcesobjectThe 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 16

Notes

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

Related recipes

In the tutorial

Thanks for reading!

Donate to the site — we work hard for you.