Deep Copy and Shallow Copy

Deep Copy and Shallow Copy

ยท

4 min read

One of the most important concept in java-script When you are dealing with java-script objects.

understanding the concepts of shallow copy and deep copy is crucial to avoid unintended side effects and unexpected behavior in your code.

1. Copying Primitives:

When you have a primitive data type (such as numbers, strings, boolean), assigning one variable to another creates a copy because primitive values are stored directly in the variable:

let original = 42;
let copy = original;

console.log(copy);  // Outputs: 42

In JavaScript, the term "copy" can refer to various operations depending on the context. Here are a few common scenarios:

1. Copying Primitives:

When you have a primitive data type (such as numbers, strings, booleans), assigning one variable to another creates a copy because primitive values are stored directly in the variable:

javascript
let original = 42;
let copy = original;

console.log(copy);  // Outputs: 42

2. Shallow Copying Objects:

For objects, a common way to create a copy is by performing a shallow copy. This means copying the properties of one object into another object. This can be done using the spread operator (...), Object.assign().

let originalObject = { key: 'value' };
let copyObject = { ...originalObject };

console.log(copyObject);  // Outputs: { key: 'value' }

if you don't use let copyObject = { ...originalObject }; there can an issue occur. Such as

let originalObject = {
  key:"value"
} 
let copyObject = originalObject;

// let copyObject = {...originalObject};

copyObject.key = "copyValue";
console.log(originalObject);  

  //output { key: 'copyValue' }

You can also remove this problem by us using Object.assign

let originalObject = { key: 'value' };
let copyObject = Object.assign({}, originalObject);

console.log(copyObject);  // Outputs: { key: 'value' }

A shallow copy creates a new object or array, but if the original contains nested objects or arrays, references to those nested structures are shared between the original and the copy. Modifying the nested structures in one affects both.

It works only a single level of object means you have object inside another object here the deep copy concept comes.

3. Deep Copying Objects:

If the object contains nested objects or arrays, a shallow copy might not be sufficient. For a complete clone, you may need to perform a deep copy. Libraries like Lodash provide _.cloneDeep() for deep copying.

let's Understand the Problem

// Simple object 
let originalObject = {
  name:"sam",
  addres:{
    city:"Gwalior",
    state:"M.P"
  }
}
console.log(originalObject);
//output
{ name: 'sam', addres: { city: 'Gwalior', state: 'M.P' } }

Do Some changes int the above object.

let originalObject = {
  name:"sam",
  addres:{
    city:"Gwalior",
    state:"M.P"
  }
}

let copyObject = originalObject;
copyObject.addres.city = "Delhi";

console.log(copyObject)
console.log(originalObject);

// output
{ name: 'sam', addres: { city: 'Delhi', state: 'M.P' } }
{ name: 'sam', addres: { city: 'Delhi', state: 'M.P' } }

means If you are changing int the copy object is reflecting in the original array and we are losing our original value. By Doing deep copy we can remove it i am going to cover two method

1-, JSON.stringify(originalObject)

let originalObject = {
  name:"sam",
  addres:{
    city:"Gwalior",
    state:"M.P"
  }
}
// Deep copy using JSON.stringify and JSON.parse
let copyObject =JSON.parse(JSON.stringify(originalObject));
copyObject.addres.city = "Delhi";

console.log(copyObject)
console.log(originalObject);

//output 
{ name: 'sam', addres: { city: 'Delhi', state: 'M.P' } }
{ name: 'sam', addres: { city: 'Gwalior', state: 'M.P' } }

Disadvantage of JSON.stringify(originalObject) Method.

let originalObject = {
  name:"sam",
  addres:{
    city:"Gwalior",
    state:"M.P",
    },
    getDAta: function(){
      return "All data is here"
    }
  }
// Deep copy using JSON.stringify and JSON.parse
let copyObject = JSON.parse(JSON.stringify(originalObject));
copyObject.addres.city = "Delhi";

console.log(copyObject)
console.log(originalObject);


//output 
{ name: 'sam', addres: { city: 'Delhi', state: 'M.P' } }
{
  name: 'sam',
  addres: { city: 'Gwalior', state: 'M.P' },
  getDAta: [Function: getDAta]
}

You can easily see that we are not getting the data form the function opps! . that the problem with JSON.stringify(originalObject) if you use time variable that is also not going to work.

Solution

You can do it by manually by doing a for loop for every copy and it a a lengthy process and time consuming process.

Here comes The lodash library provides a commonly used method for deep copying.

This ensures that modifications to the copy do not affect the original structure.

const _ = require('lodash');

let originalObject = {
  name: "sam",
  addres: {
    city: "Gwalior",
    state: "M.P",
  },
  getDAta: function () {
    return "All data is here";
  }
};
//by Lodash Lib.
let copyObject = _.cloneDeep(originalObject);
copyObject.addres.city = "Delhi";

console.log(copyObject);
console.log(originalObject);

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next ๐Ÿค“.

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!

ย