Understanding Object.assign()
A quick guide to 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()
Properties in the
target
object are overwritten by properties in thesources
if they have the same key. Later sources' properties overwrite earlier ones.Object.assign()
does not throw onnull
orundefined
sources.You can define more than one
source
. All of them will be merged into thetarget
object.It mutates the
target
object as well.This method does not create a deep copy of the
source
object.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.If the property or method is non-enumerable, it wonβt be copied.
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);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// 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! β¨