DEV Community

Cover image for Shallow Copy vs Deep Copy in JavaScript: A Practical Guide
Suvankarr Dash
Suvankarr Dash

Posted on

Shallow Copy vs Deep Copy in JavaScript: A Practical Guide

When working with arrays and objects in JavaScript, copying data incorrectly can lead to subtle and frustrating bugs. The root cause is often misunderstanding shallow copy versus deep copy.

This guide explains the difference, when to use each, and the pitfalls to avoid.

Understanding the Difference:
Shallow Copy:

A shallow copy creates a new array or object, but nested objects and arrays still reference the original memory.

This means:

  • Changes to nested values affect both the copy and the original
  • Only the top-level structure is duplicated

Deep Copy:

A deep copy creates a fully independent duplicate of the original data structure, recursively copying all nested values.

This ensures:

  • No shared references
  • Mutations do not affect the original data

When to Use Each:

Use Shallow Copy When:

  • The array contains only primitives (numbers, strings, booleans)
  • You don’t plan to mutate nested data
  • Performance and memory usage matter

Use Deep Copy When:

  • Data contains nested objects or arrays
  • You need immutable updates (e.g., React state)
  • You want full isolation between copies

JavaScript Examples:
Shallow Copy Example:

const a = [{ x: 1 }, { x: 2 }];
const b = a.slice(); // shallow copy

b[0].x = 99;
console.log(a[0].x); // 99 (shared reference)

Deep Copy Examples:

JSON-based Deep Copy (JSON-safe data only)
const deep1 = JSON.parse(JSON.stringify(a));

Limitations:

  • Loses Date, Map, Set
  • Drops functions and undefined
  • Cannot handle circular references

Modern Built-in Deep Copy:
const deep2 = structuredClone(a);

Advantages:

  • Preserves more data types
  • Handles circular references
  • Safer than JSON cloning

Performance Considerations:
Deep cloning large or complex structures is expensive. Instead of cloning everything:

  • Clone only the part you intend to change
  • Prefer shallow copy for flat data
  • Use libraries like lodash.cloneDeep for complex cases

Practical Tips:

  • Arrays of primitives → Shallow copy is enough
  • Nested objects → Use deep copy
  • Avoid JSON cloning when data types matter
  • Always consider performance when deep cloning

Final Thoughts:

  • Many state-related bugs in JavaScript happen because of unintended shared references. Knowing when to use shallow or deep copy is a foundational skill—especially in modern frameworks like React.
  • Mastering this concept will save you time, prevent bugs, and make your code more predictable.

Top comments (0)