Accidental Object Mutation Bugs
TL;DR
Objects and arrays are passed by reference in JS — mutating a function parameter or array element mutates the original, causing subtle cross-component state bugs.
Explanation
JavaScript passes objects and arrays by reference. Mutating a function parameter mutates the caller's object. Common in: React state mutations (never mutate state directly), Redux reducers, array methods (sort(), splice(), reverse() mutate in place vs map(), filter(), slice() which return new arrays). Solutions: spread to clone ({...obj}), structuredClone() for deep clone, Object.freeze() to prevent mutation, immutable patterns. Mutation detection: Redux DevTools, React StrictMode double-invokes reducers to catch mutations.
Common Misconception
✗ const prevents object mutation — const only prevents reassignment of the binding, not mutation of the object's properties.
Why It Matters
Accidental mutation causes shared state bugs where changing data in one component silently affects another — extremely hard to debug in large applications.
Common Mistakes
- Sorting arrays in place without cloning: users.sort() mutates the original.
- Mutating React state directly: state.items.push(item) — never re-renders.
- Not knowing splice() mutates but slice() doesn't.
Code Examples
✗ Vulnerable
// React anti-pattern — direct state mutation:
const [items, setItems] = useState([]);
function addItem(item) {
items.push(item); // Mutates state — React won't re-render
setItems(items);
}
✓ Fixed
// Immutable patterns:
function addItem(item) {
setItems(prev => [...prev, item]); // New array — React re-renders
}
// Sort without mutation:
const sorted = [...users].sort((a, b) => a.name.localeCompare(b.name));
// Deep clone:
const safeCopy = structuredClone(complexObject);
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Edited
5 Apr 2026
Views
54
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
No pings yesterday
Amazonbot 17
Perplexity 14
Google 6
ChatGPT 5
Unknown AI 3
Majestic 2
Ahrefs 1
Also referenced
How they use it
crawler 45
crawler_json 2
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟡 Medium
⚙ Fix effort: Medium
⚡ Quick Fix
Use spread [...arr] or {...obj} for shallow clone. Use structuredClone() for deep clone. Prefer non-mutating array methods (map, filter, slice). Freeze objects with Object.freeze().
📦 Applies To
javascript ES2015
web
cli
🔗 Prerequisites
🔍 Detection Hints
\.push\(|\.sort\(|\.splice\(
Auto-detectable:
✓ Yes
eslint
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✗ Manual fix
Fix: Medium
Context: Function
Tests: Update