BeginnerCoder

Lesson 12 — Immutable updates

Copy, do not change

Objects are passed by reference: const b = a does not copy anything, both names point at the same object, so changing b also changes a. To update immutably (without changing the original), build a new object with spread and override just the field you want.

const cart = { items: 2, paid: false };
const paidCart = { ...cart, paid: true };
console.log(cart.paid, paidCart.paid); // false true

Why it matters: React and most state libraries only notice a change when they get a new object — mutating the old one causes "my screen did not update" bugs.

Want it another way?
Task

Replace the two marked lines with one spread copy so u keeps age 30 and u2 has age 31.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.