Understanding Object.assign()

A quick guide to understanding `Object.assign()`

Understanding Object.assign()

πŸ‘‰ The Object.assign method is used to assign one or more object values to another object. It copies all the enumerable own properties and values to another object and returns the merged object.

let's take a look at the syntax.

Object.assign(target, ...sources);

πŸ‘‰ Here are some of the major points you have to remember while using Object.assign()

  1. Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.

  2. Object.assign() does not throw on null or undefined sources.

  3. You can define more than one source. All of them will be merged into the target object.

  4. It mutates the target object as well.

  5. This method does not create a deep copy of the source object.

  6. It makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the target object, instead of creating a separate new object.

  7. If the property or method is non-enumerable, it won’t be copied.

  8. None of the prototype properties and objects are added to the target object.

πŸ‘‰ Example:

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

// expected output: Object { a: 1, b: 4, c: 5 }

// expected output: Object { a: 1, b: 4, c: 5 }

I have two different objects, source, and target. The names are just for clarification. After executing the code, all the enumerable properties of the source object will are copied or assigned to the target object. You can clearly see that the contents of target objects are also changed.

That's it, folks! hope it was a good read for you. Thank you! ✨

πŸ‘‰ References:

πŸ‘‰ Follow me: