Object.assign() in JavaScript?


Object.assign()

This method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target. It returns the target object which has properties and values copied from the target object. This method does not throw on null or undefined source values.

syntax

Object.assign(target, ...source objects);

It takes source objects and a target object as parameters and push the source objects into the target object and display the target object.

Example-1

In the following example, the properties from the source objects  "obj1", "obj2", and "obj3" were pushed into a target object "obj" and the target object is returned as the output.

<html>
<body>
<script>
   var obj1 = { a: 10, b:20 };
   var obj2 = { c: 30, d:40 };
   var obj3 = { e: 50 };
   var obj = Object.assign({}, obj1, obj2, obj3);
   document.write(JSON.stringify(obj));
</script>
</body>
</html>

Output

{"a":10,"b":20,"c":30,"d":40,"e":50}


Example-2

In the following example, there are multiple instances of some of the properties of the objects. In this case the method Object.assign() takes the lastly assigned value of a property. For instance, in all the 3 objects "obj1", "obj2", and "obj3 property 'c' is common and assigned values such as 1,3 and 0 respectively. The value of property 'c' in obj3 overrides the other previously assigned values 1 and 3. So if we look at the output, property 'c' is assigned with a value 0.

<html>
<body>
<script>
   var obj1 = { a: 10, b:20, c:1 };
   var obj2 = { b: 30, d:10, c:3 };
   var obj3 = { e: 60, d:70, c:0 };
   var obj = Object.assign({}, obj1, obj2, obj3);
   document.write(JSON.stringify(obj));
</script>
</body>
</html>

Output

{"a":10,"b":30,"c":0,"d":70,"e":60}

Updated on: 20-Aug-2019

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements