Object.assign() in Javascript

Object.assign():

well, object assign in JavaScript does the shallow copy of it’s own properties and values from the sources to the target object and returns the target object.

Syntex: Object.assign(target, ...sources)

confused?? checkout the example below

const targetObj = Object.assign({}, ‘string’, null, 12, undefined,{keyObj: “valObj”},[‘string’, ‘12’, { keyArr: “keyVal” }]);

output:

0: “string”

1: “12”

2: {keyArr: “keyVal”}

3: “i”

4: “n”

5: “g”

keyObj: “valObj”

I’ve added multiple source objects just to cover all possible use cases. The first param passed is the target object and rest includes the sources. Again the source can be of any type including primitives[string, boolean, integer, symbol, null, undefined] and object types.

Couple of points to note from the produced output so as to understand it better.

The primitives will be wrapped up including the items in the array. Only the first level objects will be assigned.

To maintain unique keys it also override the keys from all sources in case of duplicates.

The null and undefined will be ignored.

The properties on the prototype chain won’t be copied.

Also we need to find alternative for the deep clone.

Hope this helps. Thank you for reading…