DEV Community

Elizabeth Onyenekwe
Elizabeth Onyenekwe

Posted on

Using Object.assign()

Recently, while working on a project, I encountered a situation where i tried to store an object in an array. After pushing that object into the array, I will return the value of the keys into an empty string. Pushing the object wasn't an issue as I used the spread operator and the push() array method and it worked. What I didn't notice was that I was making a reference to the object I was trying to push. So every time I made changes to that object, the members of the array changed too. Experiencing this bug, I understood the importance of Object.assign() and I decided to share. It might help someone who needs it too.

Object.assign() clones all enumerable properties of an object and transfers it into a target source. It invokes getters and setters thereby defining new properties in the target source.

Object.assign() is also used to merge object with same properties and the properties from the object which is cloned overwrites the properties in the target source which has the same key.

The syntax for using object.assign in your code is

object.assign(target, ...source)
Enter fullscreen mode Exit fullscreen mode

After cloning or merging an object, it returns the target.

Error

A type error can occur if the property of the target source is non-writable.

Exceptions

  1. An exception occurs if the properties of the target source are overwritten before the error is raised
  2. Object.assign does not work on null or undefined source values.

Top comments (0)