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
After cloning or merging an object, it returns the target.
A type error can occur if the property of the target source is non-writable.
- An exception occurs if the properties of the target source are overwritten before the error is raised
- Object.assign does not work on null or undefined source values.