Spread & immutable updates

Make a copy with a purpose

Lesson 14 of 20 · 11 min · Module 5: Reliable data pipelines

Two names can refer to the same object. An update through either name then changes the same data. A deliberate copy lets you create a new version instead.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Recognize shared object references
  • Copy each level being updated

The idea

Use object spread to make a shallow copy. Later properties override earlier ones: { ...settings, theme: "dark" }. Nested objects still need their own copies when you change them.

const before = { theme: "light", reminders: true };
const after = { ...before, theme: "dark" };

01Assignment does not clone

const copy = original gives the same object another name. Both variables can observe later mutations.

02Spread is shallow

A new outer object does not automatically copy its nested preferences. Copy the nested level before assigning its new dailyGoal value.

03Test the promise to callers

Keep a reference to the original preferences, call the function, and inspect both versions. A useful test checks identity as well as values.

Your turn

Write withDailyGoal(profile, goal). Return a new profile and a new nested preferences object with dailyGoal set to goal. Preserve other preferences and every other profile field. preferences may be missing. Do not mutate the input.

What the checks look for

  • Preserves other profile fields and preferences
  • Creates separate objects without changing the input
  • Handles missing preferences
Try it in the editor →

Take this with you

Copy exactly the levels you change; keep the update explicit.

Go a little further

Add a second nested preference update and test that the previous version remains unchanged.

Learn JavaScript Foundations for free

20 short lessons with real code and instant checks.

See the whole course →