Immutability
Learn to update data by copying instead of mutating it.
Immutability
Immutability means updating data by copying it instead of changing it in place. The original data is preserved and a new copy is produced. This makes it easy to track where data changed.
const user = { name: 'Alex', age: 25 };
const older = { ...user, age: 26 };Here user stays the same; older is a new object. The spread operator ...user copies all properties, then age: 26 overwrites only the age.
Spread and Object.freeze
Two common tools support immutability. The spread operator { ...obj } produces a shallow copy of an object; you add the properties you want to override afterwards.
const updated = { ...user, age: 26 };Object.freeze locks an object; any later changes are silently ignored. This is useful to prevent accidental mutation.
Exercise Write an immutable updateUser function
Write a function named updateUser. It takes user and updates parameters. It copies user with spread without mutating it, overrides with updates, and returns the new object. Then call console.log(updateUser({ name: 'Alex', age: 25 }, { age: 26 })).
Show example solution
function updateUser(user, updates) {
return { ...user, ...updates };
}
console.log(updateUser({ name: 'Alex', age: 25 }, { age: 26 }));
Test yourself
-
Which one mutates the user object?
const user = { name: 'Alex', age: 25 };- const copy = { ...user, age: 30 };
- user.age = 30;
- Object.freeze(user);
- const copy = Object.assign({}, user);
Show answer
user.age = 30; — Correct! user.age = 30 changes the existing object directly.
-
Copy with age increased by 1
const user = { name: 'Alex', age: 25 }; const older = { ...user, ____ };Show answer
const user = { name: 'Alex', age: 25 }; const older = { ...user, age: 26 }; -
Match the immutability tools
- Object.freeze
- blocks changes
- spread {...obj}
- copies to new object
- mutation
- changes existing value