Shallow Copy vs Deep Copy in JavaScript Objects

Understand the difference between shallow and deep copy in JavaScript objects. Learn when each matters, see mutation bugs in action, and pick the right method.

JavaScriptbeginner
10 min read

When you copy a JavaScript object, the depth of that copy determines whether nested data stays connected to the original or becomes fully independent. This single distinction is responsible for an entire category of bugs where modifying a "copy" accidentally changes the original data. Understanding shallow versus deep copy is not just theoretical; it affects how you write state management, API handlers, and any code that transforms data.

How JavaScript Stores Objects

Before comparing copy types, you need to understand how JavaScript handles reference types. Primitive values (numbers, strings, booleans) are stored directly in the variable. Objects are stored in heap memory, and the variable holds a pointer (reference) to that memory location:

javascriptjavascript
// Primitives: independent copies
let a = 42;
let b = a;
b = 100;
console.log(a); // 42 (unchanged)
 
// Objects: shared references
let objA = { name: "Alice" };
let objB = objA;
objB.name = "Bob";
console.log(objA.name); // "Bob" (both point to same object!)

Neither objA nor objB "owns" the object. They both reference the same data in memory. Any change through one variable is visible through the other. This is why cloning matters.

What Is a Shallow Copy?

A shallow copy creates a new object and copies all top-level properties from the source. However, if any property's value is an object (including arrays), the copy gets a reference to the same nested object, not an independent duplicate:

javascriptjavascript
const original = {
  name: "Alice",
  age: 30,
  address: {
    city: "Portland",
    state: "OR"
  },
  hobbies: ["reading", "hiking"]
};
 
// Shallow copy using spread
const shallow = { ...original };
 
// Top-level properties are independent
shallow.name = "Bob";
console.log(original.name); // "Alice" (safe)
 
// Nested objects are SHARED
shallow.address.city = "Seattle";
console.log(original.address.city); // "Seattle" (mutated!)
 
shallow.hobbies.push("coding");
console.log(original.hobbies); // ["reading", "hiking", "coding"] (mutated!)

Here is the memory model:

PropertyoriginalshallowIndependent?
name"Alice""Bob"Yes (primitive)
age3030Yes (primitive)
address{city: "Seattle"}Same objectNo (shared reference)
hobbies["reading","hiking","coding"]Same arrayNo (shared reference)

What Is a Deep Copy?

A deep copy creates an entirely new object and recursively copies every nested object and array. The result is completely independent of the original:

javascriptjavascript
const original = {
  name: "Alice",
  age: 30,
  address: {
    city: "Portland",
    state: "OR"
  },
  hobbies: ["reading", "hiking"]
};
 
// Deep copy using structuredClone
const deep = structuredClone(original);
 
// Top-level properties are independent
deep.name = "Bob";
console.log(original.name); // "Alice" (safe)
 
// Nested objects are ALSO independent
deep.address.city = "Seattle";
console.log(original.address.city); // "Portland" (safe!)
 
deep.hobbies.push("coding");
console.log(original.hobbies); // ["reading", "hiking"] (safe!)

Every level of nesting is duplicated. The deep copy shares nothing with the original.

Visual Comparison

CodeCode
SHALLOW COPY:
original โ”€โ”€> { name: "Alice", address: โ”€โ”€โ”€โ”€โ”€> { city: "Portland" }
shallow  โ”€โ”€> { name: "Bob",   address: โ”€โ”€โ”˜                        }

DEEP COPY:
original โ”€โ”€> { name: "Alice", address: โ”€โ”€> { city: "Portland" } }
deep     โ”€โ”€> { name: "Bob",   address: โ”€โ”€> { city: "Seattle"  } }

With a shallow copy, both objects share the nested address reference. With a deep copy, each has its own independent address object.

Shallow Copy Methods

JavaScript provides several ways to create shallow copies:

javascriptjavascript
const original = { a: 1, b: { c: 2 } };
 
// Method 1: Spread operator
const copy1 = { ...original };
 
// Method 2: Object.assign
const copy2 = Object.assign({}, original);
 
// Method 3: Object.fromEntries + Object.entries
const copy3 = Object.fromEntries(Object.entries(original));

All three produce the same result: top-level properties are copied by value, but nested objects share the same reference.

For arrays, the shallow copy methods are:

javascriptjavascript
const arr = [1, { x: 2 }, [3, 4]];
 
const copy1 = [...arr];
const copy2 = arr.slice();
const copy3 = Array.from(arr);
 
// All produce shallow copies
copy1[1].x = 99;
console.log(arr[1].x); // 99 (nested object shared)

Deep Copy Methods

javascriptjavascript
const original = { a: 1, b: { c: 2, d: [3, 4] } };
 
// Method 1: structuredClone (recommended)
const copy1 = structuredClone(original);
 
// Method 2: JSON round-trip (limited, legacy)
const copy2 = JSON.parse(JSON.stringify(original));
 
// Method 3: Manual recursive clone
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") return obj;
  if (Array.isArray(obj)) return obj.map(item => deepClone(item));
 
  const clone = {};
  for (const [key, value] of Object.entries(obj)) {
    clone[key] = deepClone(value);
  }
  return clone;
}
const copy3 = deepClone(original);

Deep Copy Method Comparison

MethodHandles DatesHandles Map/SetHandles FunctionsCircular RefsSpeed
structuredClone()YesYesNo (throws)YesMedium
JSON.parse(JSON.stringify())No (to string)No (to {})No (removed)No (throws)Slow
Manual recursive cloneYes (with code)Yes (with code)Yes (with code)No (unless tracked)Varies

When Shallow Copy Is Enough

Shallow copies work perfectly for flat objects with only primitive values:

javascriptjavascript
// Safe with shallow copy - all primitives
const settings = {
  theme: "dark",
  fontSize: 16,
  autoSave: true,
  volume: 0.8
};
 
const copy = { ...settings };
copy.theme = "light";
console.log(settings.theme); // "dark" (safe)

Shallow copies also work when you replace (not mutate) nested objects:

javascriptjavascript
const state = {
  user: { name: "Alice" },
  count: 0
};
 
// Replacing the entire nested object is safe with shallow copy
const newState = {
  ...state,
  user: { ...state.user, name: "Bob" }  // New object, not mutation
};
 
console.log(state.user.name); // "Alice" (safe)

This "spread at each level" pattern is exactly what React and Redux use for immutable state updates.

When You Need Deep Copy

Deep copies are necessary when:

  1. You mutate nested data after copying
  2. You pass objects to functions that might modify nested properties
  3. You cache or snapshot complex state for undo/redo
  4. You receive data from an API and need multiple independent transformations
javascriptjavascript
// Undo/redo history needs deep copies
const history = [];
 
function saveSnapshot(state) {
  history.push(structuredClone(state));
}
 
function undo() {
  if (history.length === 0) return null;
  return history.pop();
}
 
const appState = {
  canvas: {
    shapes: [
      { type: "circle", x: 10, y: 20, radius: 5 },
      { type: "rect", x: 30, y: 40, width: 10, height: 15 }
    ]
  }
};
 
saveSnapshot(appState);                          // Save state
appState.canvas.shapes[0].x = 100;               // Move circle
saveSnapshot(appState);                          // Save new state
const previousState = undo();                    // Restore
console.log(previousState.canvas.shapes[0].x);   // 100

Real-World Example: API Data Transformer

Here is a practical example where shallow vs deep copy matters when processing API responses:

javascriptjavascript
function processOrderData(apiResponse) {
  // Deep clone because we'll modify nested arrays
  const orders = structuredClone(apiResponse.data.orders);
 
  return orders.map(order => {
    // Calculate totals by modifying the cloned data
    order.items.forEach(item => {
      item.total = item.price * item.quantity;
      item.taxAmount = item.total * 0.08;
      item.finalPrice = item.total + item.taxAmount;
    });
 
    order.subtotal = order.items.reduce((sum, item) => sum + item.total, 0);
    order.tax = order.items.reduce((sum, item) => sum + item.taxAmount, 0);
    order.grandTotal = order.subtotal + order.tax;
 
    return order;
  });
}
 
const rawResponse = {
  data: {
    orders: [
      {
        id: "ORD-001",
        items: [
          { name: "Laptop", price: 999, quantity: 1 },
          { name: "Mouse", price: 29, quantity: 2 }
        ]
      }
    ]
  }
};
 
const processed = processOrderData(rawResponse);
 
// Original API data is untouched
console.log(rawResponse.data.orders[0].items[0].total); // undefined (safe!)
console.log(processed[0].grandTotal);                   // 1143.72

Without the deep clone, calling processOrderData would permanently modify the original API response, which could corrupt cached data or break other parts of your application.

Performance Considerations

OperationRelative SpeedMemory Impact
Reference assignment (=)InstantNone (no copy)
Shallow copy (spread)Very fastMinimal (one level)
Deep copy (structuredClone)5-20x slower than shallowFull duplication
Deep copy (JSON round-trip)10-50x slower than shallowString + object allocation

For most applications, the speed difference is negligible. A deep clone of a typical API response takes microseconds. Only optimize if profiling shows cloning as a bottleneck in a hot path (like inside a loop processing thousands of objects).

Common Mistakes to Avoid

Assuming Spread Creates Deep Copies

javascriptjavascript
const data = { config: { debug: true } };
const copy = { ...data };
copy.config.debug = false;
console.log(data.config.debug); // false - BUG!

Using JSON Round-Trip Without Checking Types

javascriptjavascript
const data = {
  date: new Date(),
  count: undefined,
  valid: NaN
};
 
const clone = JSON.parse(JSON.stringify(data));
console.log(typeof clone.date);  // "string" (not Date)
console.log("count" in clone);   // false (undefined removed)
console.log(clone.valid);        // null (NaN became null)

Forgetting That Arrays Are Objects Too

javascriptjavascript
const original = { tags: ["js", "web"] };
const shallow = { ...original };
 
shallow.tags.push("react");
console.log(original.tags); // ["js", "web", "react"] - BUG!
 
// Arrays inside objects need deep clone too
const safe = structuredClone(original);
safe.tags.push("react");
console.log(original.tags); // ["js", "web"] - safe

Decision Flowchart

  1. Is the object flat (no nested objects or arrays)? Use spread { ...obj }
  2. Do you need all nested data independent? Use structuredClone()
  3. Are you doing immutable state updates (replacing, not mutating nested data)? Spread at each level is fine
  4. Does the data contain functions? Use spread (shallow) or build a custom cloner
  5. Working with JSON-safe data in an older environment? JSON.parse(JSON.stringify()) works

Best Practices

  1. Default to spread for flat objects. It is the fastest and most readable shallow copy method.
  2. Use structuredClone() for nested data. It is the standard deep clone with the best type support.
  3. Prefer immutable update patterns over deep cloning. Spreading at each level ({ ...state, user: { ...state.user, name: "new" } }) is more efficient than deep cloning the entire state tree.
  4. Clone at boundaries, not everywhere. Clone when data crosses ownership boundaries (API responses, function inputs you do not control) rather than copying every object defensively.
  5. Test mutations explicitly. When writing functions that transform data, verify that the original input is unchanged after the function returns.
Rune AI

Rune AI

Key Insights

  • Shallow copy shares nested references: modifying a nested property in the copy also modifies the original, causing hard-to-find bugs
  • Deep copy creates full independence: structuredClone() is the modern standard that handles Date, Map, Set, and circular references
  • Spread at each level is an alternative: for state management, spreading only the changed levels is more efficient than deep cloning everything
  • JSON round-trip is a legacy approach: it destroys Date, Map, Set, undefined, NaN, and functions, so use structuredClone instead
  • Clone at boundaries, not everywhere: clone data when it crosses ownership boundaries (API calls, shared state) rather than defensively copying every object
RunePowered by Rune AI

Frequently Asked Questions

Is structuredClone always better than JSON.parse(JSON.stringify)?

For new code, yes. `structuredClone()` correctly handles Date objects, Map, Set, circular references, and more types that JSON destroys. The only reason to use the JSON method is if you need to run in an environment that does not support `structuredClone` (Node.js < 17, very old browsers) and cannot use a polyfill.

Does the spread operator deep copy arrays inside objects?

No. The [spread operator](/tutorials/programming-languages/javascript/js-spread-operator-for-arrays-complete-tutorial) only copies the top level. Arrays inside objects remain as shared references. If you modify `copy.items.push(newItem)`, the original array is also modified. Use `structuredClone()` when your object contains nested arrays.

How does React handle shallow vs deep copy in state?

React uses shallow comparison (`Object.is`) to detect state changes. That is why React state updates use the spread-at-each-level pattern: `setState(prev => ({ ...prev, user: { ...prev.user, name: "new" } }))`. This creates new objects only at the levels that changed, which is more efficient than deep cloning the entire state tree.

Can I use lodash cloneDeep instead of structuredClone?

Yes, Lodash's `_.cloneDeep()` works reliably and handles edge cases that `structuredClone` does not (like cloning functions and preserving class prototypes). However, it adds a dependency (4KB+ for just `cloneDeep`). For most projects, `structuredClone` covers enough use cases to avoid the extra dependency.

How do I clone an object with getters and setters?

Neither spread, `Object.assign`, `structuredClone`, nor JSON preserve getters and setters. They all evaluate the getter and copy the resulting value. To preserve accessor descriptors, use `Object.defineProperties(clone, Object.getOwnPropertyDescriptors(original))` which copies the descriptor objects including getters and setters.

Conclusion

The difference between shallow and deep copy in JavaScript determines whether nested data stays connected to the original or becomes fully independent. Shallow copies (spread, Object.assign) duplicate top-level properties but share nested objects. Deep copies (structuredClone) recursively duplicate everything. Choosing correctly prevents the mutation bugs that are among the hardest to diagnose in JavaScript applications.