learn deep. ship safe.Practice testsFollow ByteMunSubscribe

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

  • const stops the variable being reassigned. It does not stop the object it points to from changing.
  • Object.freeze prevents 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 are toSorted, toReversed and toSpliced.
  • 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 const make 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.

Concept map
Learn firstObjects
Immutability and copying

What should you learn before Immutability and copying?

  1. ObjectsCollections of key–value properties, the building block of most JavaScript data.

Practise Immutability and copying

All topics