JAVASCRIPT / CHAPTER 09
Object identity and deliberate nested updates
IntermediatePredict which mutations are visible through shared references.
By the end of this chapter
- Trace aliases
- Recognize shallow copies
- Copy every changed path
The idea
Two variables can refer to the same object, and equality tests that identity rather than comparing all fields. An array or object spread creates a new outer container, but nested objects remain shared. Before updating a record, draw the references: identify the outer object, each nested object, and which aliases can observe a mutation.
For an immutable update, replace the containers along the changed path and retain unaffected references deliberately. This approach preserves the original without claiming that every nested value was deeply copied. It also makes tests precise: verify both the changed result and the unchanged input. Data copied from a boundary still needs validation; copying is an ownership decision, not proof that its fields are valid.
const old = {id: 1, settings: {volume: 3}};
const next = {...old, settings: {...old.settings, volume: 5}};
console.log(old.settings.volume, next.settings.volume);
console.log(old.settings === next.settings);3 5 false
The inner spread makes a distinct settings object before replacing volume.
Try it yourself
Update one item in an array of records without changing the input array or the changed record.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING