0

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;

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Because if you don't:

clone.name = "Tom";
console.log(person.name) => "Tom"

IOW, it will be the same object, with a different name.

2 Comments

So changing person also changes the clone?
Yes, it's just an alias

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.