Simple Example -> Shallow Copy and Deep Copy in JavaScript
Shallow Copy
An object is called to be shallow copied when the properties are copied without any reference
It only copies the Object Properties not the reference.
When you change the Object properties on one place it reflects everywhere , because it has a reference.
Simple Example -> var rootObject = {name:’Abhijit’,age:’31'}
Here if i want to shallow copy the “rootObject” simply i can write
var shallowObject = Object.assign(rootObject) // shallow copy
if i change here the properties of rootObject.age = 32 & do a console log
console.log(shallowObject) i will get below result
{
name:”Abhijit”,
age:32
}
Deep Copy
Deep Copy duplicate every object it encounters. The copy and the original object has different reference address.
Simple Example
var rootObject = {name:’Abhijit’,age:’31'}
if we want to deep copy this object we can do it in two ways (There can be multiple ways)
1st way
var deepCopyObject = JSON.parse(JSON.stringify(rootObject))
So here the two Objects has different reference address
Here if i change the property of rootObject
rootObject.age = 32 and do a console log for both rootObject and deepCopyObject .. You will see only rootObject property is getting changed not the deepCopyObject because both reference address is different.
console.log(rootObject)
{
name:”Abhijit”,
age:32
}
console.log(deepCopyObject) // unchanged
{
name:”Abhijit”,
age:31
}
2nd Way
var rootObject = {name:’Abhijit”,age:31}
var deepCopyObject = deepCloneObject(rootObject)
function deepCloneObject(object){
var clone = {}
for(var i in object){
if(object != null && typeof(object[i]) == “object”){
clone[i] = cloneObject(object[i])
}else{
clone[i] = object[i]
}
}
return clone
}
console.log(rootObject)
console.log(deepCloneObject)