foundation
Object immutability
Mutation, shallow copies, Object.freeze, structural sharing, and application-state trade-offs.
Immutability means producing new values instead of mutating shared state. JavaScript supports this via spread, `Object.assign`, `Object.freeze`, TypeScript `readonly`, or libraries like Immer.
Structural sharing reuses unchanged branches. UI frameworks detect changes by reference equality on top-level state.
`JSON.parse(JSON.stringify(obj))` loses functions, `undefined`, `Date`, `Symbol`, and prototypes.
Local mutation inside a function is fine when the state does not escape.
On interviews, explain the concept with a concrete example and name the runtime behavior interviewers probe.
Common pitfalls include mixing similar APIs and forgetting edge cases during live coding.
The trade-off is often clarity versus performance or safety versus convenience.
Checklist:
- Define the mutation boundary.
- Prefer structural sharing for state updates.
- Do not use JSON clone as default.