01 / 20

Avoiding State
Mutation

Learn why mutating shared state leads to bugs, and how to write code with clear, predictable data flow instead.

JavaScript

What Is State?

State is any data your program remembers over time: a user's name, a shopping cart, a counter value, or even a configuration object. Whenever your code reads or writes to a variable that holds information, it is interacting with state.

Local State
Lives inside a single function. Only that function can see or change it.
Shared State
Accessible by multiple functions or modules. Changes here can ripple outward.

What Is Mutation?

Mutation means changing an existing value in place. In JavaScript, objects and arrays are stored by reference: when two variables point to the same object, changing it through one variable affects the other.

const user = { name: "Alice", score: 10 }; const ref = user; // same object in memory ref.score = 99; // mutates the original! console.log(user.score); // 99 <-- surprise!

Why Does This Matter?

Unintended mutation is one of the most common sources of bugs in JavaScript applications. When shared state changes unexpectedly, you get:

Invisible Bugs
A function changes data used elsewhere. The error appears far from the actual cause.
Race Conditions
In async code, two callbacks may modify the same object at the same time, creating unpredictable results.
Hard Debugging
You cannot tell when or where the state changed, because nothing logged the mutation.

The Core Rule

MUTATION (avoid) Original Object Changed in place! COPY (prefer) Original Object New Copy Untouched

Clear Data Flow

Instead of many functions reaching into the same mutable object, design your code so that data flows in one direction: each function takes input, returns new output, and never touches the original.

Input functionA() returns new functionB() returns new Output One-Way Data Flow Original input is never modified

Mutable vs Immutable Patterns

Mutable Immutable
Add to array arr.push(item) [...arr, item]
Remove from array arr.splice(i, 1) arr.filter(x => x !== val)
Update object field obj.key = val {...obj, key: val}
Sort an array arr.sort() [...arr].sort()
Predictability Low High

How to Apply This

1
Identify shared state. Find any variable or object that more than one function reads or writes.
2
Copy before changing. Use spread (...) or methods like Object.assign, slice, map, or filter to create a new value.
3
Return the copy. Have your function return the new value instead of mutating the input in place.
4
Use const by default. Declaring with const signals that the binding will not change. (It does not prevent object mutation, but it shows intent.)
5
Freeze when needed. For truly read-only data, use Object.freeze() to make mutations throw errors in strict mode.

Example 1: Arrays

A function needs to add a new item to a list. Compare the mutating approach with the immutable approach.

✕ Mutating
function addTodo(list, task) { list.push(task); // modifies the original array return list; }
vs
✓ Immutable
function addTodo(list, task) { return [...list, task]; // new array, original intact }

Example 2: Objects

A function updates a user's email. The mutating version overwrites the field directly. The immutable version returns a fresh object.

✕ Mutating
function updateEmail(user, email) { user.email = email; // mutates the original return user; }
vs
✓ Immutable
function updateEmail(user, email) { return { ...user, email }; // new object }

Example 3: Nested Objects

Nested data requires spreading at every level you change. A shallow spread only copies the top layer: inner objects are still the same references.

const state = { user: { name: "Alice", prefs: { theme: "dark" } } }; // Correct: spread at every changed level const next = { ...state, user: { ...state.user, prefs: { ...state.user.prefs, theme: "light" } } };

Object.freeze() as a Safety Net

Object.freeze() makes an object immutable at the top level. In strict mode, any attempt to change a frozen property throws a TypeError.

"use strict"; const config = Object.freeze({ apiUrl: "https://api.example.com", retries: 3 }); config.retries = 5; // TypeError: Cannot assign
Pros
Catches accidental mutations at runtime. Great for configuration objects or constants.
Limits
Only freezes the top level. Nested objects remain mutable unless you recursively freeze them.

The Big Picture

Strategies for Avoiding Mutation Spread Operator {...obj} [...arr] Shallow copy Pure Methods map filter slice Return new arrays Object.freeze() Runtime protection Top-level only Predictable State Fewer bugs, easier testing Easy Undo/Redo Time-Travel Debug Safe Concurrency

Common Mistakes

✕ Shallow Copy Only
Using {...obj} copies only the first level. Nested objects still share references and can be mutated.
✕ Forgetting .sort() Mutates
Array.sort() and .reverse() modify the original array in place. Always copy first: [...arr].sort().
✕ Thinking const Prevents Mutation
const prevents reassignment of the variable. It does not prevent changing the object's properties.

Summary Table

Concept Key Idea
State Data your program remembers over time
Mutation Changing a value in place, by reference
Shared State Risk One change can break distant code
Immutable Pattern Copy first, then modify the copy
Spread (...) Shallow clone of objects and arrays
Object.freeze() Prevents top-level property changes
Nested Updates Spread at every changed level

Question 1 of 5

What does it mean to mutate a value in JavaScript?

Question 2 of 5

What does console.log(original.length) print?

Question 3 of 5

Which of the following creates a new array instead of mutating the original?

Question 4 of 5

What is the main limitation of Object.freeze()?

Question 5 of 5

After this code runs, what is the value of state.user.age?