menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:Shallow vs. deep cloning

menu

Cloning in JavaScript refers to creating a copy of an object, array, or data structure. When it comes to cloning, there are two important concepts: shallow cloning and deep cloning. These concepts describe the extent to which the cloning process replicates the original data structure. Let's dive deeper into the differences between shallow cloning and deep cloning:

Shallow Cloning:

Shallow cloning creates a new object or array that is a copy of the original top-level structure. However, it doesn't duplicate the nested objects or arrays within the structure. Instead, it copies references to these nested objects. In other words, changes made to the nested objects in the cloned structure will affect the original structure, and vice versa.

JavaScript provides various methods for shallow cloning:

1. Spread Operator (...): This is commonly used for shallow cloning in ES6.

javascriptconst originalArray = [1, 2, [3, 4]];
const shallowCopy = [...originalArray];

shallowCopy[0] = 5; // Modify the top-level property
shallowCopy[2] = [8,9]; // Modify a nested property in the copied object

console.log(originalArray ); // Output: [1, 2, [8, 9]]
console.log(shallowCopy);   // Output: [5, 2, [8, 9]

2. Object.assign(): For objects, you can use Object.assign() to create a shallow copy.

javascriptconst originalObject = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, originalObject); // Using Object.assign()

shallowCopy.a = 5; // Modify the top-level property
shallowCopy.b.c = 3; // Modify a nested property in the copied object

console.log(originalObject); // Output: { a: 1, b: { c: 3 } }
console.log(shallowCopy);   // Output: { a: 5, b: { c: 3 } }

Deep Cloning:

Deep cloning creates a completely independent copy of the original data structure, including all nested objects and arrays. Changes made to the cloned structure do not affect the original, and vice versa. Deep cloning is particularly useful when you need to work with complex and nested data structures.

In JavaScript, achieving deep cloning can be more complex.

One common approach is to use a recursive function to traverse the structure and create copies of all nested objects and arrays.

Another approach is to serialize the original structure to JSON and then parse it back into an object, creating a deep copy.

1. Example of deep cloning using recursion:

javascriptfunction deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj; // Base case: primitive values or null
  }

  if (Array.isArray(obj)) {
    const copy = [];
    for (const item of obj) {
      copy.push(deepClone(item));
    }
    return copy;
  } else {
    const copy = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        copy[key] = deepClone(obj[key]);
      }
    }
    return copy;
  }
}

const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = deepClone(originalObject);

deepCopy.a = 5; // Modify the top-level property
deepCopy.b.c = 3; // Modify a nested property in the copied object

console.log(originalObject); // Output: { a: 1, b: { c: 2 } }
console.log(deepCopy);       // Output: { a: 5, b: { c: 3 } }

2. Example of deep cloning using serialize:

javascriptfunction deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = deepClone(originalObject);

deepCopy.a = 5; // Modify the top-level property
deepCopy.b.c = 3; // Modify a nested property in the copied object

console.log(originalObject); // Output: { a: 1, b: { c: 2 } }
console.log(deepCopy);       // Output: { a: 5, b: { c: 3 } }

Considerations:

  • Shallow cloning is more performant and suitable for simple data structures, while deep cloning is necessary for complex, deeply nested data.

  • When working with shallow clones, be cautious of unintended side effects due to shared references.

  • Deep cloning can be more resource-intensive, so it should be used judiciously, especially for large data structures.

  • Be aware of circular references (objects that reference themselves) when implementing deep cloning, as this can lead to infinite recursion.

In summary, the choice between shallow and deep cloning in JavaScript depends on your specific use case and the nature of your data. Understanding the differences between these two approaches is essential for effective data manipulation and maintaining data integrity in your applications.

1280 x 720 px