Skip to content

JavaScript object assign() | Method

  • by

JavaScript object assign() method is used to copy all enumerable own properties of given objects to a single 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 given object.

Object.assign(target, ...sources)

The method copies only the enumerable properties of the source objects, and it does not copy inherited properties. If a property with the same name already exists in the target object, its value will be overwritten by the value in the last source object.

Example JavaScript object assign

Simple example code copies the values of all enumerable properties from one or more source objects to a target object.

<!DOCTYPE html>
<html>
<body>

  <script>
    const target = { a: 1, b: 2 };
    const source = { b: 4, c: 5 };

    const returnedTarget = Object.assign(target, source);

    console.log(target);
    console.log(source);
    console.log(returnedTarget);
  </script>

</body>
</html> 

Output:

Creating a target object and copying values from the other 2 objects’ properties to it using the object.assign() method.

<script>
    var obj1 = { a: 10 };
    var obj2 = { b: 20 };
    var obj3 = { c: 30 };

    var new_obj = Object.assign({}, obj1, obj2, obj3);

    console.log(new_obj);
</script>

Output: { a: 10, b: 20, c: 30 }

Another example

const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5 };

Object.assign(target, source1, source2);

console.log(target); // { a: 1, b: 3, c: 4, d: 5 }

Do comment if you have any doubts or suggestions on this JS Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading