Concept
Immutability and copying
Changing data by making new copies instead of editing in place; shallow vs deep copies.
Immutability and copying explained
Immutability means not changing data in place: instead of editing an object or array, you create a new one with the change. This makes it easy to tell when something changed (a new reference means new data), avoids bugs where two parts of a program share and modify the same object, and is how React decides what to re-render.
How to update data immutably
const user = { name: "Asha", tags: ["js"] };
// Mutating (avoid): the same object changes under everyone holding it
// user.name = "Ravi";
// Immutable updates: new objects, the original untouched
const renamed = { ...user, name: "Ravi" };
const tagged = { ...user, tags: [...user.tags, "react"] };
const removed = user.tags.filter((t) => t !== "js");
const sorted = [...user.tags].sort(); // sort() mutates, so copy first
Shallow and deep copies
Spread (...) and Object.assign make shallow copies: the top level is new, but nested objects are still shared. To change something nested, copy each level on the path to it. structuredClone(value) makes a full deep copy when you really need one.
const and Object.freeze
conststops the variable being reassigned. It does not stop the object it points to from changing.Object.freezeprevents changes to an object's own properties, but only one level deep.
Common mistakes
- Mutating React state (
state.items.push(x)) and wondering why the screen does not update. - Using array methods that mutate (
sort,reverse,splice) on shared data. Their copying counterparts aretoSorted,toReversedandtoSpliced. - Assuming a spread copy is deep.
What interviewers ask about immutability
- "Shallow copy or deep copy?" Explain what is shared after a spread.
- "Why does React need immutable updates?" It compares references to decide whether state changed.
- "Does
constmake an object immutable?" No, only the binding.
Immutability outside React
The same idea makes code easier to reason about anywhere. Redux reducers return new state objects, so time-travel debugging and undo work. Functions that never change their inputs are easier to test and safe to call from several places at once, and immutable values can be cached because they cannot change underneath the cache.
What should you learn before Immutability and copying?
- ObjectsCollections of key–value properties, the building block of most JavaScript data.
Practise Immutability and copying
- Intermediate JavaScript Interview Questions3 questions on Immutability and copying
- Top 20 JavaScript interview questions with answers: core JS, Node.js and React1 question on Immutability and copying
- Advanced JavaScript Interview Questions1 question on Immutability and copying