Course contentsShow
← JavaScript
Lesson 1761 of 2,72337. Functional Programming PatternsFree lesson

Immutable Object Updates: Nested Properties

Update nested object properties immutably by spreading at each level to avoid shared references.

Immutable Object Updates: Nested Properties

You'll learn how to update deeply nested object properties without mutating the original, avoiding accidental shared references.

The Core Problem

When objects contain nested objects, a simple spread only copies the top level—inner objects remain shared references. If you mutate a nested property, you've changed the original structure, breaking immutability.

Think of it like photocopying a folder: you get a new folder, but the documents inside are still the same physical papers. To truly duplicate everything, you need to copy each level.

The Solution: Spread at Every Level

To update a nested property immutably, spread from the outermost object down to the property you're changing:

const user = {
  name: 'Alice',
  address: {
    city: 'Boston',
    zip: '02101'
  }
};

// ❌ BAD: Shallow spread doesn't protect nested objects
const bad = { ...user };
bad.address.city = 'NYC'; // Mutates original!

// ✅ GOOD: Spread at each level
const updated = {
  ...user,
  address: {
    ...user.address,
    city: 'NYC'
  }
};

console.log(user.address.city);    // 'Boston' (unchanged)
console.log(updated.address.city); // 'NYC'

Each spread creates a new object at that level, breaking the reference chain. The original remains untouched.

For deeply nested structures, continue the pattern:

const state = { user: { profile: { theme: 'dark' } } };

const newState = {
  ...state,
  user: {
    ...state.user,
    profile: {
      ...state.user.profile,
      theme: 'light'
    }
  }
};

Key Takeaway: Update nested properties immutably by spreading at every level from the root down to the target property—this creates new objects at each layer and preserves the original structure.