The Object.assign(targetObj, sourceObjs…) method

The Object.assign() method is used is used to copy the values of all enumerable own properties from one or more source objects to a target object. This method will return targetObj. Here is an example which demonstrates this:

let x = {x: 12};let y = {y: 13, __proto__: x};let z = {z: 14, get b() {return 2;}, q: {}};Object.defineProperty(z, "z", {enumerable: false});let m = {};Object.assign(m, y, z);console.log(m.y);console.log(m.z);console.log(m.b);console.log(m.x);console.log(m.q == z.q);

The output is as follows:

13undefined2undefinedtrue

Here is a list of important things to keep in mind while using the Object.assign() method:

  • It invokes getters on the sources and setters on the target. ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.