Deep Copy vs Shallow Copy in JavaScript?: Understanding the Difference

Deep Copy vs Shallow Copy in JavaScript: Understanding the Difference

In JavaScript, copying objects and arrays is a common task. However, understanding the difference between shallow copy and deep copy is crucial to avoid unintended side effects in your code

What is a Shallow Copy?

A shallow copy creates a new object or array with the same references as the original. This means that if the original object contains nested objects or arrays, the reference is copied, not the actual values. Any modifications made to the nested objects will reflect in both copies.

const original = {
    name: "Harshit",
    details: {
        age: 25,
        city: "Lucknow"
    }
};

const shallowCopy = { ...original };
shallowCopy.details.city = "Delhi";

console.log(original.details.city); // Output: "Delhi"
console.log(shallowCopy.details.city); // Output: "Delhi        

Other Methods to Create Shallow Copy:

  • Object.assign(): const shallowCopy = Object.assign({}, original);
  • Array Methods: slice(), map(), filter(), etc., work for arrays.

What is a Deep Copy?

A deep copy means that all objects and nested objects are fully cloned, rather than just copying references. Changes in the new object do not affect the

const original = {
    name: "Harshit",
    details: {
        age: 25,
        city: "Lucknow"
    }
};

const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.details.city = "Delhi";

console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"        

Drawbacks of JSON.parse(JSON.stringify()):

  • Cannot handle functions, undefined, NaN, Infinity, or Date objects.
  • Performance issues for large objects.

How to Properly Create a Deep Copy?

If you need a deep copy that handles complex data types like functions and Date objects, use libraries or recursion.

Method 1: Using Lodash cloneDeep

Lodash provides an efficient deep copy function.

const _ = require('lodash');
const deepCopy = _.cloneDeep(original);
deepCopy.details.city = "Delhi";

console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"        

Method 2: Using a Recursive Function

If you want a custom deep copy function, you can use recursion.

function deepClone(obj) {
    if (obj === null || typeof obj !== "object") {
        return obj;
    }
    
    let copy = Array.isArray(obj) ? [] : {};
    
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            copy[key] = deepClone(obj[key]);
        }
    }
    
    return copy;
}

const deepCopy = deepClone(original);
deepCopy.details.city = "Delhi";

console.log(original.details.city); // Output: "Lucknow"
console.log(deepCopy.details.city); // Output: "Delhi"        

要查看或添加评论,请登录

Harshit Pandey的更多文章

社区洞察

其他会员也浏览了