Shallow Copy VS Deep Copy

Shallow Copy:

Shallow copy is copying only top-level elements. In shallow copy, if there are two variables present both are referencing the same object.

Deep Copy:

Deep copy is copying nested elements also. In a deep copy, two different references objected created with the same properties and values.

Top-level element examples:

var array1 = ["apple", "banana"];
var object1 = {size: "100%", owner: "hashnode" };

Nested elements example:

var array2 = ["apple", "banana", ['100','200'];
var object2 = {size: "100%", owner: "hashnode", ages: [1,2,3] };

Now we see some examples in Array and Objects:

Array:

Shallow Copy:

It will affect only top-level elements, no nested elements.

1. Array.concate(Array1):

var org = [100,200, {'a': 'notchanged'}];
var otherArray = ['hashnode'];
var concatedArray = otherArray.concat(org);

concatedArray[0] = 'concat';
concatedArray[3]['a'] = 'change';

//console.log(concatedArray);
//console.log(org);

//Output:
['concat', 100, 200, {'a': 'change'}];
['concat', 100, 200, {'a': 'change'}];

So you can see I changed data in one of the variables and it automatically changed the other variable data. It happened because both variables reference the same object. And it means that from Concat you can only do Shallow Copy. It is not allowed to do Deep Copy.

Here I am listing more methods you can read about it.

  1. Array.from(Array1)
  2. Array.slice(0);
    //0 is here index
    
  3. Spread Operator [...Array1]
//Example:
var org = [1,3,4, {'a': "apple"}];
var spreadOperator = [...org];

Deep Copy:

1. Json.parse(JSON.stringify(Array1);

This will create another object with the same values and properties.

Object:

Shallow Copy:

It will affect only top-level elements, no nested elements.

1. Object.assign({}, sourceObj);

var sourceObj = {
     age: 1,
     gender: 'male',
     skill: ['write','speak']           
}

var copiedObj = Object.assign({}, sourceObj);
copiedObj.age = '1000';
copiedObj.skill[0] = 'code';

//console.log(sourceObj);
//console.log(copiedObj);

//output:
{age: 1, gender: 'male', skill: skill: ['code','speak']}
{age: 1000, gender: 'male', skill: skill: ['code','speak']}

You can see it affected only top elements. In both objects top elements are different. But we also tried to make changes in a nested element and we can see it made changes in both objects. Which gives only Shallow Copy not Deep Copy.

Here I am listing more methods you can read about it.

  1. Spread Operator {...obj}

Deep Copy:

1. Json.parse(JSON.stringify(obj);

This will create another object with the same values and properties.

Thank You that's all from my side.