There are two ways, we can copy the object in javascript, first is by using the assignment operator i.e. ‘=’ and the second is by using the ‘clone’ function. In this article, we’ll discuss what is the difference between both of them.
By using the _.clone() function: Both of these methods copy objects but they are very different from each other. This method creates a new object and copies the value of an old object into it, so if there is any change in the old object then it does not affect the content of the new object. The _.clone() method is used to create a shallow copy of the value.
Example:
Javascript
<script> const _ = require( "lodash" ); var original = { Name: "Aman" , color: "Black" }; var duplicate = _.clone(original); console.log(duplicate); original.Name = "Vivek" ; console.log(duplicate); </script> |
Output:
{ Name: 'Aman', color: 'Black' } { Name: 'Aman', color: 'Black' }
As we can see in this example, if we use clone-function then the duplicate object doesn’t get affected by it.
By using the assignment operator: This method is different from the clone function as we use the ‘=’ operator in this for coping the object and if we try to change the original object then the duplicate objects also get changed with it. We can see this in the example below.
Example:
Javascript
<script> var original = { Name: "Aman" , color: "Black" }; var duplicate = original; console.log(duplicate); original.Name = "Vivek" ; console.log(duplicate); </script> |
Output:
{ Name: 'Aman', color: 'Black' } { Name: 'Vivek', color: 'Black' }
As we can see in this example, when we try to change the content of the original object then that change also gets reflected in the duplicate object.