JavaScript: Object.assign

By Xah Lee. Date: . Last updated: .

New in JS2015.

Object.assign( target_obj, source_obj_1, source_obj_2 etc )
Merge objects. Shallow copy all enumerable own properties from source objects to target object. If property keys clash, later sources overwrites earlier ones.
Return the modified target_obj.
[see Property Attributes]

Shallow copy means, if a source object contains a key whose value is object objX, the result will have objX as a reference, not creating new object, meaning, if objX is modified, it'll show up in both source and result object.

// merge objects into a new object
console.log(Object.assign({}, { a1: 3 }, { b1: 3 })); // { a1: 3, b1: 3 }
// modify a existing object by merging new ones
const aa = { a1: 3 };
const bb = { b1: 3 };
const cc = { c1: 3 };

const tt = { a1: 999 };

Object.assign(tt, aa, bb, cc);
console.log(tt); // { a1: 3, b1: 3, c1: 3 }
// key a1 is overwritten
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Object Object

prototype