Mutable data can be changed in place, while immutable data is never modified — instead, new copies are created. Understanding this difference is critical for predictable state management in React, Angular, Redux/NgRx, and for avoiding side effects and hard-to-debug bugs.
Mutability vs Immutability in JavaScript (State, References, and Side Effects)
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The core difference
- Mutable data can be changed in place.
- Immutable data is never modified; instead, you create a new value.
In JavaScript, objects and arrays are mutable by default. Most bugs in UI state management come from mutating something you thought was 'a copy'.
Concept | What it means | Example |
|---|---|---|
Mutation | Changing the same object in memory |
|
Immutability | Creating a new object instead of changing the old one |
|
Mutation in action (the bug factory)
const state = {
user: { name: 'Alice' },
loggedIn: true
};
const nextState = state; // NOT a copy, same reference!
nextState.user.name = 'Bob';
console.log(state.user.name); // 'Bob' ❗ original is changed
Immutable update (correct pattern)
const state = {
user: { name: 'Alice' },
loggedIn: true
};
const nextState = {
...state,
user: {
...state.user,
name: 'Bob'
}
};
console.log(state.user.name); // 'Alice' ✅
console.log(nextState.user.name); // 'Bob'
Why frameworks care so much
React, Angular (OnPush), Redux, NgRx, etc. rely heavily on reference equality checks (===) to detect changes.
If you mutate in place:
- The reference stays the same
- Change detection may not run
- UI gets out of sync
Operations: mutable vs immutable
Operation | Mutable | Immutable alternative |
|---|---|---|
Add to array |
|
|
Remove from array |
|
|
Sort array |
|
|
Update object field |
|
|
Performance reality
- Naive deep copying everything is slow.
- Real-world immutable systems use structural sharing: only copy the path you change, reuse the rest.
Libraries like Immer let you write “mutating” code that produces immutable results under the hood.
Important nuance
Immutability is a discipline, not a JavaScript language rule. const does not make objects immutable — it only prevents reassigning the variable.
const obj = { x: 1 };
obj.x = 2; // allowed ❗
One-sentence answer
Mutable data is changed in place, while immutable data is never modified — instead, you create new values and keep the old ones untouched, enabling predictable state and cheap change detection.