Friday, June 19, 2026
HomeLanguagesJavascriptDifference between copying an object through assignment operator and _.clone() function ?

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

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6898 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6965 POSTS0 COMMENTS