JS Object.assign()

JS Object.assign()

·

1 min read

Table of contents

No heading

No headings in the article.

Twitter Youtube

Properties in target object are overwritten by properties in the sources if they have the same key.

Reference

1.jpeg

Alternatively, we can use spread operator.

2.png

Must use empty object as first param as it is the target into which every source properties will be copied (set).

Object.assign(target, source1, source2....);

Otherwise the object positioned in target will get mutated like below:

3.jpeg

Don't deep clone using object.assign. It can stop mutating first hand object whereas it can allow mutating nested objects like.

4.jpeg

Native alternative for deep clone would be JSON.parse.

5.jpeg