Course contentsShow
← JavaScript
Lesson 975 of 2,72322. Spread and RestFree lesson

Spread with Nested Objects

Understand that spread only copies the first level, leaving nested objects as shared references.

Spread with Nested Objects

What you'll learn: How the spread operator handles nested objects and why it can create unexpected shared references.

The Shallow Copy Problem

When you spread an object, JavaScript only copies the first level of properties. If a property's value is itself an object (or array), the spread operator doesn't create a new copy of that nested structure—it copies the reference to it instead.

This means the original and the "copy" both point to the same nested object in memory. Changes to the nested object in one place will appear in the other.

const user = {
  name: 'Alice',
  address: {
    city: 'Paris',
    zip: '75001'
  }
};

const userCopy = { ...user };

// Top-level properties are independent
userCopy.name = 'Bob';
console.log(user.name); // 'Alice' ✓

// But nested objects are SHARED
userCopy.address.city = 'London';
console.log(user.address.city); // 'London' ⚠️

Why This Happens

Think of spread like photocopying a document that has a sticky note attached. The photocopy includes everything on the page, but the sticky note itself isn't duplicated—both documents reference the same physical note. Moving the note affects both "copies."

Working Around It

To truly copy nested objects, you need to spread at each level manually, or use techniques like structuredClone() or JSON serialization (if appropriate).

const deeperCopy = {
  ...user,
  address: { ...user.address }
};

Key Takeaway: The spread operator performs a shallow copy—nested objects remain shared references between the original and the copy, so modifying nested properties affects both.