DEV Community

Sonu kumar
Sonu kumar

Posted on

What is the difference between a deep copy and a shallow copy in JavaScript?

Deep Copy And Shallow 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 variable that means we are copying the reference of that variable, which means we are not creating the new variable for that just assigned the reference of the variable.

So when we made the changes on the copied variable object/ array it also gets changes on the original variable value, which is known as Shallow Copy if when are any changes on the copied variable then not getting any changing the original variable values are 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 changes:
  copyUserObj.name = "jhon de-costa"

  console.log(userObj);
  output:
  {
    "name": "Jhon De-costa",
    "address": {
      "city": {
        "name": "Noida"
      }
    }
  }


  To avoid these things we deep copy using the ES6 spread operator:

  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 comment I will clear your doubts;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)