What is difference between deep copy vs Shallow copy in Javascript?
Shallow Copy & Deep Copy:
Sometimes we need to copy the value from one variable to another variable is known as copy. But when we are copying the value from one variable to another varaibale that means we are copy the refrence of that varaible, that means we are not creating the new varaiable for that just assigned the refrence of the varaiable.
So when we made the chnges on copied variable object/ array its also get chnges on original varaible value , that is known as Shallow Copy if when does any changes on copied varaible and then not getting any changing the original varaibale values is known as Deep Copy
Example: how to make the deep copy and shallow copy:
//original
var userObj = {
name:"jhon",
address:{
city: {
name:"Noida"
}
}
}
//wanted to copy
var copyUserObj = userObj; // shallow copy
///Here we are doing the chnges:
copyUserObj.name = "jhon de-costa"
console.log(userObj);
output:
{
"name": "Jhon De-costa",
"address": {
"city": {
"name": "Noida"
}
}
}
to avoiding these thing we deep copy using ES6 spred oprator:
copyUserObj = {...userObj}
copyUserObj.name = "jhon de-costa"
console.log(userObj)
output:
{
name:"jhon",
address:{
city: {
name:"Noida"
}
}
}
console.log(copyUserObj)
output:
{
"name": "Jhon De-costa",
"address": {
"city": {
"name": "Noida"
}
}
}
Ex:2
var arr1 = [1, 2, 4]
//Wanted to copy here array to arr2
var arr2 = arr1;
arr2[1] = 4
console.log(arr1);
output:
[1,4,4]
//deep copy using spred {...} oprator
arr2= [...arr1];
console.log(arr2)
output:
[1,2,4]
//after modifcation of arr2 the value
var arr2 = [1,4,4]
console.log(arr1)
output:
[1,2,4]
console.log(arr2)
output:
[1,4,4]
if you have any doubts please commnets I will clear your doubt;
0 Comments