DEV Community

Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on

Deep Copy vs Shallow Copy in JavaScript

πŸ“ Definitions

  • Shallow copy A new object is created, but its nested objects/arrays are still referenced (not copied).
  • Deep copy A new object is created, and all nested objects/arrays are recursively copied, so they are fully independent.

πŸ“¦ Shallow Copy Examples

const obj = { user: "Ali", settings: { theme: "dark" } };

// Shallow copies
const copy1 = { ...obj };
const copy2 = Object.assign({}, obj);

copy1.user = "Sara";
console.log(obj.user); // "Ali" (independent primitive)

copy1.settings.theme = "light";
console.log(obj.settings.theme); // "light" (nested object was shared!)
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Only the top-level properties are copied. Nested references still point to the same objects.


πŸ“¦ Deep Copy Examples

Using structuredClone (modern JS)

const obj = { user: "Ali", settings: { theme: "dark" } };
const deepCopy = structuredClone(obj);

deepCopy.settings.theme = "light";
console.log(obj.settings.theme); // "dark" βœ… independent
Enter fullscreen mode Exit fullscreen mode

Using JSON trick (not recommended for all cases)

const deepCopy = JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

⚠️ This fails with Date, Map, Set, undefined, functions, circular references.

Using libraries

  • Lodash: _.cloneDeep(obj)
  • Immer: handles immutable updates with deep cloning.

πŸ›‘ Pitfalls of Shallow Copy

  • Mutating nested structures leaks changes:
  const state = { user: { name: "Ali" } };
  const next = { ...state };
  next.user.name = "Sara";

  console.log(state.user.name); // "Sara" ❌ unexpected mutation
Enter fullscreen mode Exit fullscreen mode
  • In React/Redux, this can cause stale renders because React thinks the state is unchanged (reference is same).

βœ… When to Use

  • Shallow copy is fine when:

    • Object has only primitives.
    • You don’t need to mutate nested structures.
    • Performance is critical and you control object shape.
  • Deep copy is needed when:

    • You must ensure no shared references.
    • Working with nested state in frameworks (e.g., Redux).
    • Serializing complex objects (careful with special types).

πŸ” Performance Considerations

  • Deep copy is slower and heavier because it traverses entire object trees.
  • Shallow copy is cheap, just reassigns top-level references.

βœ… Summary

  • Shallow copy: Copies top-level properties only; nested objects are shared.
  • Deep copy: Recursively copies everything; no shared references.
  • Use shallow copy for flat/simple objects, and deep copy when you need complete independence.

✨ Rule of thumb: If you change a nested value and don’t want it to affect the original β†’ you need a deep copy.

Originally published on: Bitlyst

Top comments (0)