Immutable updates & Object.freeze
Changes without surprises
Lesson 15 of 20 · 11 min · Module 4: Reliable code
Bugs where "something changed somewhere" are among the hardest to find. Updating data by creating new objects, instead of changing existing ones, keeps every earlier version intact.
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…
- Update nested data without mutation
- Understand structural sharing
- Freeze data deeply
The idea
An immutable update copies only the path that changes and reuses every untouched part, which is called structural sharing. Object.freeze(obj) prevents changes to an object, but only at the top level; freezing nested data needs recursion.
const state = { user: { name: "Ana" }, theme: "light" };
const next = { ...state, theme: "dark" };
console.log(state.theme, next.theme, next.user === state.user);
01Copy the path, share the rest
Changing user.prefs.theme creates a new root, a new user, and a new prefs object. The cart array is reused as it is, so copying stays cheap even for large data.
02Cheap change detection
Because untouched parts keep their identity, a program can check next.cart === state.cart to know the cart did not change. Interfaces built with React rely on exactly this.
03freeze is shallow
Object.freeze stops changes to the object’s own properties only. Nested objects are still editable until you freeze them too, which is why deepFreeze recurses.
const o = Object.freeze({ inner: { x: 1 } });
o.inner.x = 2;
console.log(o.inner.x);2Your turn
setIn(obj, path, value) where path is an array of keys. Return a new object with the value set at that path, creating missing objects, without changing the input, and reusing untouched branches. Write deepFreeze(obj) that freezes an object and every nested object or array, and returns it.What the checks look for
- Sets a nested value in a new object
- Reuses branches that did not change
- Creates missing levels
- deepFreeze freezes every level and returns the object
- Frozen data cannot be changed in strict mode
Take this with you
Make new versions instead of editing old ones.
Go a little further
Write updateIn(obj, path, fn) that sets the value to fn(oldValue).