ilyo ilyo - 1 year ago 87
Javascript Question

What is the difference between deep and shallow cloning?

If I use splice to clone an array it gives me a shallow copy, what is missing? It seems I get back multilevel arrays so it is not the depth of the array if I understand correctly.

Answer Source

In a shallow copy, if arrays (or object properties) are references to objects, then only the references are copied.

var a = [{name: "Bob"}];
var b = a.slice(0);
b[0].name = "Tom";
alert(a[0].name); // "Tom"

A "deep" copy makes sure that the result contains new copies of all referenced objects from the original data structure. Performing a deep copy can be problematic, depending on the nature of the objects involved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download