HomeJAVASCRIPTDifference between shallow copy and deep copy.

Difference between shallow copy and deep copy.

The difference between shallow copy and deep copy mainly revolves around how nested objects (or references) are copied. Let’s break it down clearly:


1. Shallow Copy

  • Definition: Creates a new object, but the top-level elements only are copied. If the object contains nested objects (like arrays, objects), the copy shares references to the same nested objects instead of creating new ones.
  • Effect: Changes in nested objects affect both the original and the copied object.
  • Methods in JavaScript:
    • Object.assign({}, obj)
    • Spread operator: { ...obj }
    • Array: [...arr]

Example:

let original = { a: 1, b: { c: 2 } };
let shallow = { ...original };

shallow.a = 10;           // Only shallow copy is affected
shallow.b.c = 20;         // Both original and shallow are affected

console.log(original.b.c); // 20

2. Deep Copy

  • Definition: Creates a completely independent copy of the object, including all nested objects. Changes in the copy do not affect the original object.
  • Effect: No shared references; fully independent.
  • Methods in JavaScript:
    • JSON.parse(JSON.stringify(obj)) (simple objects)
    • Using libraries like Lodash: _.cloneDeep(obj)

Example:

let original = { a: 1, b: { c: 2 } };
let deep = JSON.parse(JSON.stringify(original));

deep.b.c = 20;

console.log(original.b.c); // 2 (original unaffected)

Summary Table

FeatureShallow CopyDeep Copy
Copies nested objects?No, only referencesYes, fully independent
Effect on original if nested changesChanges reflectNo effect
PerformanceFaster (less memory)Slower (more memory)
MethodsObject.assign, ...JSON.parse(JSON.stringify), _.cloneDeep

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *