When copying values in JavaScript, particularly for non-primitive data types like objects and arrays, it's crucial to understand the distinction between shallow copy and deep copy. Shallow copy and deep copy are often discussed in programming interviews, and you may be asked to write a deep copy function from scratch.
In a shallow copy, the copied object (object B) has a different reference than the original object (object A), but their structure remains the same in the prototype chain. However, the actual addresses of their properties differ. This means that when copying values, if there are nested objects, a shallow copy only copies the references to the first level of properties, not the actual values of nested objects.
In contrast, a deep copy creates a completely new object with its own unique memory space, ensuring that both the original and copied objects have distinct references and property addresses. This means that even for nested objects, the deep copy recursively copies the values of all nested properties, breaking any shared references.
clone and cloneDeep FunctionsLodash, a popular JavaScript utility library, provides two distinct functions for copying objects: clone and cloneDeep.
clone: This function performs a shallow copy, only copying the references to the first level of properties.cloneDeep: This function performs a deep copy, recursively copying the values of all nested properties.// Shallow copy with lodash's clone
var objects = [{ a: 1 }, { b: 2 }];
var shallow = _.clone(objects);
console.log(objects === shallow); // false (different references)
console.log(shallow[0] === objects[0]); // true (same reference for the first-level object)
// Deep copy with lodash's cloneDeep
var objects = [{ a: 1 }, { b: 2 }];
var deep = _.cloneDeep(objects);
console.log(objects === deep); // false (different references)
console.log(deep[0] === objects[0]); // false (different references for the first-level object)
JSON.**stringifyUsing JSON Stringify and Parse for Deep Copy in JavaScript:
One approach to perform a deep copy of an object in JavaScript is to utilize the JSON.stringify and JSON.parse functions. This method involves serializing the object into a JSON string using JSON.stringify and then deserializing the string back into an object using JSON.parse.
Steps:
JSON.stringify(object). This step converts the object's structure and data into a text representation.JSON.parse(jsonString). This step reconstructs the object's structure and data from the JSON string.