JavaScript Object.assign()

The JavaScript Object.assign() method copies all enumerable own properties of given objects to a single object and returns it.

The syntax of the assign() method is:

Object.assign(target, ...sources)

The assign() method, being a static method, is called using the Object class name.


assign() Parameters

The assign() method takes in:

  • target - The target object — what to apply the sources' properties to, which is returned after it is modified.
  • sources - The source object(s) — objects containing the properties you want to apply.

Return value from assign()

  • Returns the target object.

Note: Properties in the target object are overwritten by properties in the sources if they have the same key.


Example 1: Using Object.assign() to clone & merge objects

// cloning objects
const obj = {
  name: "Alan Turing",
  age: 120,
};

let newObject = {};

const copy = Object.assign(newObject, obj);
// modifies the target object
console.log(newObject);
// returns the modified object
console.log(copy);

// merging objects
const o1 = { a: 1, b: 2, c: 3 };
const o2 = { b: 12, c: 13 };
const o3 = { c: 23 };

// Earlier source keys are overwritten by later sources
const o4 = Object.assign({}, o1, o2, o3);

console.log(o4); // { a: 1, b: 12, c: 23 }

Output

{ name: 'Alan Turing', age: 120 }
{ name: 'Alan Turing', age: 120 }
{ a: 1, b: 12, c: 23 }

Note here that if the source value is a reference to an object, it only copies the reference value.

Also, later sources' properties overwrite earlier ones.


Example 2: Using Object.assign()

const obj = Object.create(
  { a: 1 },
  {
    // a is on obj's prototype chain.
    b: {
      value: 2, // b is a non-enumerable property.
    },
    c: {
      value: 3,
      enumerable: true, // c is an own enumerable property.
    },
  }
);

let copy = Object.assign({}, obj);
console.log(copy); // { c: 3 }

copy = Object.assign(copy, "abc", 100, null);
console.log(copy); // { '0': 'a', '1': 'b', '2': 'c', c: 3 }

Output

{ c: 3 }
{ '0': 'a', '1': 'b', '2': 'c', c: 3 }

As you can see, properties on the prototype chain and non-enumerable properties cannot be copied.

Also, primitives will be wrapped to objects, null and undefined are ignored.

Since only strings have enumerable property, they get copied to target object.


Recommended Reading: Javascript Object defineProperties()

Did you find this article helpful?