Implementing Deep Cloning in JavaScript: A Comprehensive Guide

Implementing Deep Cloning in JavaScript: A Comprehensive Guide

·

2 min read

Deep cloning is a fundamental concept in JavaScript, especially when dealing with complex data structures. Unlike shallow cloning, which creates a copy of the original object with references to the same nested objects, deep cloning creates a completely independent copy, including all nested structures. In this blog post, we'll delve into the concept of deep cloning in JavaScript and explore an implementation using the provided code.

Understanding the Code: Let's begin by analyzing the provided code for deep cloning:

export default function deepClone(value) {
  if (typeof value !== 'object' || value === null) {
    return value;
  }

  if (Array.isArray(value)) {
    return value.map((item) => deepClone(item));
  }

  return Object.fromEntries(
    Object.entries(value).map(([key, value]) => [key, deepClone(value)]),
  );
}

Explanation:

Base Case Check:

  • The function begins by checking if the provided value is not an object or is null. If true, it means the value is a primitive type, and a direct copy is returned.

Array Handling:

  • If the value is an array, the Array.isArray check ensures that each element in the array is also deeply cloned using the map function.

Object Handling:

  • For objects, the code utilizes Object.entries to get an array of [key, value] pairs. The map function is then applied to each pair, recursively calling deepClone on the nested values. Finally, Object.fromEntries is used to convert the array of [key, value] pairs back into an object.

Using the deepClone Function: Now that we understand how the deepClone function works, let's see how it can be employed in practical scenarios:

const originalObject = {
  name: 'John',
  age: 25,
  address: {
    city: 'Example City',
    country: 'Sample Country',
  },
};

const clonedObject = deepClone(originalObject);

console.log(clonedObject);

/*{
   name: 'John',  
   age: 25,
   address: {
   city: 'Example City',
   country: 'Sample Country'
}*/

Did you find this article valuable?

Support Md Talha by becoming a sponsor. Any amount is appreciated!