Which method in ES6 is used to copy an object?

Using Object.assign() Method to Copy Objects in ES6

The Object.assign() method in ES6 is used to copy an object. This is a built-in JavaScript method that introduced in ECMAScript2015 (ES6). A common misconception is using Object.copy(), Object.clone(), or Object.duplicate(), but these methods don't exist in JavaScript. The correct way to create a copy of an object is to use Object.assign() method.

Understanding Object.assign() Method

This method copies all enumerable own properties from one or more source objects to a target object and returns the target object. The syntax is as follows:

Object.assign(target, ...sources);
  • target: The target object.
  • ...sources: The source object(s).

The method treats both the target and sources as objects by first converting them to objects.

Practical Example

Here is an example of how to use Object.assign():

let obj1 = {
  a: 1,
  b: 2
};

let obj2 = Object.assign({}, obj1);

console.log(obj2); // {a: 1, b: 2}

In the above example, an empty object {} is used as the target, and obj1 is the source. As a result, obj2 becomes a copy of obj1.

Best Practices

It's important to note that Object.assign() method only copies properties to a shallow level. This means that if source objects contain properties whose values are objects themselves, then the method will copy references to those objects, not duplicate the actual objects. To perform a deep copy (copying the nested objects too), one could use other methods like JSON serialization or employing a utility library function like lodash's _.cloneDeep() function.

Moreover, JavaScript also supports the spread syntax {...obj} for object literals in newer versions, which can be used as an alternative to Object.assign(). For example:

let obj1 = {
  a: 1,
  b: 2
};

let obj2 = {...obj1};

console.log(obj2); // {a: 1, b: 2}

In conclusion, Object.assign() is a powerful method in ES6 for copying objects, it is simple to use but requires caution to avoid problems related with shallow copy.

Do you find this helpful?