Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Object

Object.assign() method

Reference for JavaScript Object.assign(): copying enumerable own properties onto a target, merging objects, shallow copy limits, getters and spread comparison.

Object.assign() copies the own, enumerable properties (string and symbol keys) from one or more source objects onto a target object, then returns the target. It mutates the target. Sources are applied left to right, so later sources overwrite earlier ones.

JavaScript
Object.assign(target, source1, source2)

Try it

JS Merging and overwriting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Shallow copy, getters and symbols

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Object.assign(target)
Object.assign(target, ...sources)
Name Description
target The object that receives the properties. Primitives are converted to wrapper objects; null and undefined throw.
sources Zero or more objects whose own enumerable properties are copied. null and undefined sources are ignored.

Return value: the target object (after conversion to an object, if it was a primitive).

Exceptions: TypeError if target is null or undefined, or if a property cannot be written (read-only property, frozen or non-extensible target). Properties copied before the failure stay copied; there is no rollback.

Usage notes

  • Mutates the target. To avoid changing an existing object, pass a fresh {} as the target or use { ...a, ...b }.
  • Shallow. Nested objects and arrays are copied by reference. Use structuredClone() for a deep copy of plain data.
  • Reads getters, writes values. A getter on a source is called and its result is stored as a plain data property on the target. Use Object.defineProperties() with Object.getOwnPropertyDescriptors() to copy accessors as accessors.
  • Uses assignment, not definition. Setters on the target run, and writing to an inherited read-only property fails. Object spread, in contrast, defines properties and never triggers setters.
  • Prototype is not copied. Only own properties travel, so class instances lose their methods in a plain-object copy.
  • Order of keys. Integer-like keys come first in ascending order, then string keys in insertion order, then symbols.
  • Array targets. Object.assign([1, 2, 3], [4, 5]) overwrites by index and returns [4, 5, 3].
  • Common use is applying default options to a config; the spread form is now more popular in new code.

Browser support

Supported in every current browser (ES2015).