What is Javascript Object.assign?


In this article, we look at what the Javascript Object.assign method is and what it does. Post which, we shall dive into the code, and lastly, we shall look at its limitations.

Table of Contents

What is Javascript Object.assign?

The Javascript Object.assign is a method that copies all the properties from one or more source objects and stores them into a target object. And while working with multiple sources, the latter source properties overwrite the earlier ones. However, bear in mind that the Object.assign method only copies enumerable and own properties from the source object.

In case you are curious about how the Object.assign method assigns properties, it involves getters and setters subsequently it gets the properties from the source using [[Get]] and stores them in the target using [[Set]].

Syntax of Javascript Object.assign

Object.assign(target, ...sources)

The parameters used are explained below:

Target - The Target Object is where the copied source properties are stored and returned when the object.assign is used.

Source - The Source Objects are the objects from which the values and properties have to be copied. Unlike the Target, multiple source objects parameters can be passed.

Code and its explanation:

const target = { Dog: 5, Cat: 6 };
const source = { Cat: 10, Mouse: 5 };
const returnedTarget = Object.assign(target, source);
// expected output: Object { Dog: 5, Cat: 10, Mouse: 5 }

Cloning an Object using Javascript Object.assign

Since it copies values and properties, Object.assign can be used to clone objects.

const flexiple = { freelancer: 5 };
const clone = Object.assign({}, flexiple);
// expected output:  { freelancer: 5 }

Limitations and caveats

  • A TypeError is thrown in case the property is non-writable, however, in such case, the target object would still contain properties of the previously added values
  • Object.assign() does not throw errors on null or undefined sources
  • Ensure that the source object you are trying to clone is not a reference to an object, since it would only copy the reference values