This post explains the difference between shallow copy and deep copy in javascript.
Shallow Copy
Shallow copy means copy only the reference.
var original = {"prop1" : "Prop1", "prop2" : "prop2"};
console.log(JSON.stringify(original));
// {"prop1" : "Prop1", "prop2" : "prop2"}
var shallowCopy = original;
console.log(JSON.stringify(shallowCopy));
// {"prop1" : "Prop1", "prop2" : "prop2"}
shallowCopy.prop1 = "ChangedProp1";
console.log(JSON.stringify(original));
// {"prop1" : "ChangedProp1", "prop2" : "prop2"}
console.log(JSON.stringify(shallowCopy));
// {"prop1" : "ChangedProp1", "prop2" : "prop2"}
Notes:
- In shallow copy, original and copied object shares the same properties.
- Shallow copy only copies the object reference.
- In Shallow copy, Change in copied object reflects in original object and vice versa.
- Arrays and Object in Javascript performs the Shallow copy by default.
Deep Copy
Deep copy means copy the object properties recursively into the new object. We are going to use $.extend
method from jQuery to perform deep copy in javascript objct.
$.extend(deepCopy, target, object1, [objectN] )
- To perform deeop copy, indicate first argument as true.
- target to copy everything into.
- target1 … targetn to copy from.
var original = {"prop1" : "Prop1", "prop2" : "prop2"};
console.log(JSON.stringify(original));
// {"prop1" : "Prop1", "prop2" : "prop2"}
var deepCopy = $.extend(true, {}, original);
console.log(JSON.stringify(deepCopy));
// {"prop1" : "Prop1", "prop2" : "prop2"}
deepCopy.prop1 = "ChangedProp1";
console.log(JSON.stringify(original));
// {"prop1" : "Prop1", "prop2" : "prop2"}
console.log(JSON.stringify(deepCopy));
// {"prop1" : "ChangedProp1", "prop2" : "prop2"}
Notes:
- In deep copy, original and copied object do not share properties.
- Deep copy copies the object properties recursively.
- In deep copy, Change in copied object does not reflect in original object and vice versa.
- All primitive data types in javascript performs deep copy by default. Boolean, Null, Undefined, Number, String etc… are Primitive data types in javascript.