Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Difference between copying an object through assignment operator and _.clone() function ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.


My Personal Notes arrow_drop_up
Last Updated : 07 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials