Object.assign()

Copies properties from one or more objects into a target object.

Returns
The target object.
Changes the original
Yes
On this page

Example

#
JavaScript
const defaults = { theme: 'dark', sound: true }
const saved = { sound: false }

const settings = Object.assign({}, defaults, saved)
console.log(settings)
console.log({ ...defaults, ...saved })
Console
{ theme: 'dark', sound: false }
{ theme: 'dark', sound: false }

Definition and usage

#

The Object.assign(target, ...sources) method copies own, enumerable properties from the source objects into the target object, and returns that object. For repeated keys, later sources overwrite earlier ones.

Note that the target object gets modified. To create a new object instead, pass an empty object as the target: Object.assign({}, a, b). In modern code, the { ...a, ...b } syntax does the same thing.

The copy is shallow. Nested objects aren’t cloned, only shared. For a deep copy, use structuredClone().

Syntax

#
Syntax
Object.assign(target, source1, source2, …)

Parameters

#
  • target

    object

    The object the properties will be copied into. It will be modified.
  • source1…sourceN

    objects

    The objects the properties are copied from.

More examples

#
A shallow copy
JavaScript
const original = { name: 'Emma', stats: { level: 3 } }
const copy = Object.assign({}, original)

copy.stats.level = 10
console.log(original.stats.level)
Console
10

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To merge objects, the { ...a, ...b } syntax is used more often these days, since it doesn’t mutate either one.
  • For a copy that includes nested objects, use structuredClone().

Related entries

#

Spotted a mistake or missing an example? Write to us.