Search code examples
javascriptcopyclone

Why would you want to deep-clone a JavaScript object rather than just make a copy?


What is the point of deep-cloning a JavaScript object? If you want a copy, why not just declare another variable and set its value to the original object?

Essentially, why would you want to do this:

var person = {name: "Jean", age: 47};
var clone = $(person).clone();

When this seems more simple:

var person1 = {name: "Jean", age: 47};
clone = person1;

Solution

  • Assignment Case:

    var person1 = {name: "Ben", age: 23};
    var clone = person1;
    

    When doing an assignment with an object to a new variable, that new variable will contain the reference to the object. In this case, the variable 'clone' will refer to the same object as person1 does. So basically both person1 and clone point to the same object and any changes done to either variable will change the person object they both point to.

    Clone Case:

    var person = {name: "Ben", age: 23};
    var clone = $(person).clone();
    

    Here the object person is cloned and returns a reference to a new object with the same exact properties the person object holds. So, what this means is that both person and clone contain a reference to their own unique object and changes done to one will not affect the other.