# What is the use of OBJECT.assign() in javascript?

JavascriptFront End TechnologyObject Oriented Programming

The Object.assign() method is used to copy the values of all of the object's own properties(enumerable only) from one or more source objects to a target object. It will return the target object.

## Example

const targetObj = { a: 1, b: 2 };
const sourceObj = { b: 4, c: 5 };
const returnedTarget = Object.assign(targetObj, sourceObj);
console.log(targetObj);
console.log(returnedTarget);
console.log(returnedTarget === targetObj);
console.log(sourceObj);

## Output

{ a: 1, b: 4, c: 5 }
{ a: 1, b: 4, c: 5 }
true
{ b: 4, c: 5 }

Note

• sourceObj did not change.

• returnedTarget and targetObj are the same.

• The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters.

Published on 17-Sep-2019 08:55:08