Sub topic 5
Managing Side Effects
The previous chapter defined pure functions and referential transparency. Real programs still have to read files, call APIs, write to databases, and print output. A program with no side effects can't do anything useful. Functional programming doesn't try to remove side effects. It tries to control where they happen.
This chapter assumes you know what a pure function is, can use spread syntax to copy objects and arrays, and can run JavaScript in Node.js 20 or later. One example uses toSorted, which needs Node 20 or later.
What Counts as a Side Effect
A side effect is anything a function does that the caller can see, other than returning a value. It also covers anything the function depends on other than its arguments. Some effects are obvious, like network calls. Others are easy to miss.
| Effect | Example | Why it breaks purity |
|---|---|---|
| Output | `console.log`, writing a file, `fetch` POST | Changes the world outside the function |
| Input | Reading a file, `fetch` GET, `process.env` | Result depends on something other than arguments |
| Mutating arguments | `arr.sort()`, `obj.count++` | The caller's data changes |
| Shared state | Reading or writing a module-level variable | Result depends on call history |
| Time | `Date.now()`, `new Date()` | Different result on every call |
| Randomness | `Math.random()`, `crypto.randomUUID()` | Different result on every call |
| DOM access | `document.querySelector`, setting `innerHTML` | Reads and writes global page state |
Throwing an exception is sometimes counted as an effect too, because it changes control flow outside the return value. This chapter focuses on the categories in the table.
Spotting Mixed Responsibilities
Most real functions mix decision-making with effects. Here is a typical example. It decides whether a user can redeem a reward, and it also performs the redemption.
const db = new Map([['ada', { name: 'Ada', points: 120 }]]);
function redeemReward(userId) {
const user = db.get(userId); // input: shared state
if (user.points < 100) {
console.log(`${user.name} has too few points`); // output
return false;
}
user.points -= 100; // mutation
user.lastRedeemed = new Date().toISOString(); // time
console.log(`${user.name} redeemed a reward`); // output
return true;
}
console.log(redeemReward('ada')); // true
console.log(redeemReward('ada')); // false (same input, different result)The business rule here is "a user with at least 100 points can spend 100 points for a reward." That rule fits in one line, but it is mixed in with five different effects. You can't test the rule without a populated db, you can't check lastRedeemed without mocking the clock, and every test prints to the console.
Functional Core, Imperative Shell
The standard fix is to split the code into two layers:
- The functional core holds the decisions and calculations. It contains only pure functions that take plain data and return plain data.
- The imperative shell is a thin outer layer. It gathers input (reads the database, checks the clock), calls the core, and then carries out the effects the core's result describes.
Here is the reward example after the split:
// Functional core: pure, no I/O, no mutation
const REWARD_COST = 100;
const redeem = (user, now) =>
user.points < REWARD_COST
? { ok: false, user, message: `${user.name} has too few points` }
: {
ok: true,
user: { ...user, points: user.points - REWARD_COST, lastRedeemed: now },
message: `${user.name} redeemed a reward`
};
// Imperative shell: all effects live here
function redeemReward(db, userId, clock = () => new Date().toISOString()) {
const user = db.get(userId);
if (!user) throw new Error(`Unknown user: ${userId}`);
const result = redeem(user, clock());
db.set(userId, result.user);
console.log(result.message);
return result.ok;
}
// Testing the core needs no setup and no mocks
const ada = { name: 'Ada', points: 120 };
const fixedTime = '2026-01-01T00:00:00.000Z';
const r = redeem(ada, fixedTime);
console.log(r.user.points, r.user.lastRedeemed); // 20 2026-01-01T00:00:00.000Z
console.log(ada.points); // 120 (original untouched)
// Running the shell
const db = new Map([['ada', { name: 'Ada', points: 120 }]]);
console.log(redeemReward(db, 'ada')); // logs "Ada redeemed a reward", then trueThree things changed:
- The clock is an argument (
now) instead of a call inside the function. The shell decides where time comes from, and a test can pass a fixed value. - The core returns a new user object instead of changing the old one. The shell decides whether to save it.
- The log message is data in the result. The core doesn't decide how or where it gets printed.
The shell still has no tests of its own, but it has almost no logic to get wrong. It reads, delegates, and writes.
Injecting Time and Randomness
Time and randomness are the effects that most often slip into code that looks pure. The fix is the one used above: pass the value in, or pass in a function that produces it.
// Hidden dependency on Math.random
const rollImpure = (sides) => Math.floor(Math.random() * sides) + 1;
// The random source is a parameter with a sensible default
const roll = (sides, random = Math.random) => Math.floor(random() * sides) + 1;
console.log(roll(6)); // 1 to 6, varies
console.log(roll(6, () => 0)); // 1, always
console.log(roll(6, () => 0.99)); // 6, alwaysThe default parameter keeps normal call sites short. Strictly speaking, roll with the default is still impure. What matters is that the impurity is now a visible, replaceable input. Tests can make the function deterministic without patching globals.
Describing Effects as Data
Sometimes the core has to decide which effects happen, not only what data to compute. Instead of performing those effects, the core can return descriptions of them, and the shell interprets the list. This is the idea behind Redux middleware, Elm commands, and many workflow engines.
// Core: decides what should happen, does none of it
const checkout = (cart, now) => {
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const effects = [
{ type: 'save', key: `order:${now}`, value: { total, at: now } },
{ type: 'log', text: `Order total: ${total}` }
];
if (total > 100) {
effects.push({ type: 'email', to: '[email protected]', text: `Big order: ${total}` });
}
return effects;
};
// Shell: an interpreter that maps each effect type to a real action
const runEffects = (effects, handlers) => {
for (const effect of effects) handlers[effect.type](effect);
};
const store = new Map();
const realHandlers = {
save: (e) => store.set(e.key, e.value),
log: (e) => console.log(e.text),
email: (e) => console.log(`(pretend email to ${e.to}) ${e.text}`)
};
const cart = [{ price: 40, qty: 2 }, { price: 30, qty: 1 }];
runEffects(checkout(cart, 1700000000000), realHandlers);
// Order total: 110
// (pretend email to [email protected]) Big order: 110
// In a test, just inspect the returned array
console.log(checkout([{ price: 5, qty: 1 }], 0).map((e) => e.type)); // [ 'save', 'log' ]Building a local effects array with push is fine. The array is created inside the call and never escapes before it is returned, so no caller can observe the mutation. Purity is about what the caller can see, not about avoiding every assignment.
Async Effects
Promises don't change the pattern. Keep await in the shell and the core synchronous:
// Stand-in for a real network call
const fetchPrices = async () => ({ apple: 0.5, pear: 0.75 });
// Pure core
const priceList = (prices, items) =>
items.map((name) => `${name}: ${prices[name] ?? 'n/a'}`);
// Shell
async function main() {
const prices = await fetchPrices();
for (const line of priceList(prices, ['apple', 'kiwi'])) console.log(line);
}
main(); // apple: 0.5, then kiwi: n/aIf async starts spreading through your core functions, an effect has probably leaked inward. Move the await up a level and pass the resolved value down.
Common Mistakes
Hidden argument mutation
Several built-in array methods mutate the array in place: sort, reverse, splice, push, pop, shift, unshift, and fill. When you call one of them on an argument, the caller's data changes.
const topScores = (scores) => scores.sort((a, b) => b - a).slice(0, 2);
const scores = [3, 9, 5];
console.log(topScores(scores)); // [ 9, 5 ]
console.log(scores); // [ 9, 5, 3 ] (caller's array was reordered)
const topScoresSafe = (scores) => scores.toSorted((a, b) => b - a).slice(0, 2);Use toSorted, toReversed, and toSpliced (ES2023), or copy first with [...scores].
Debug logging left in the core
A console.log left inside a pure function is a small side effect, and it is usually harmless while you debug. Remove it before you commit, or route logging through the shell. Otherwise test output gets noisy and the function quietly depends on a global console.
Shallow copies that share nested data
{ ...user } copies only the top level. If the core then does copy.tags.push('x'), it mutates the original's tags array. Copy every level you change, as shown in the Immutability chapter.
Effects in callbacks
Callbacks passed to map or filter should be pure. A map callback that also writes to a database runs its effect once per element. It is easy to run it more times than you expected, or to run it on items you later discard.
Exercises
Exercise
List every side effect in this function, then rewrite it as a pure core plus a one-line shell call. function greet() { const name = document.getElementById('name').value; const hour = new Date().getHours(); document.body.textContent = (hour < 12 ? 'Good morning, ' : 'Hello, ') + name; }
Show answer
Effects: reading the DOM (getElementById(...).value), reading the clock (new Date()), and writing the DOM (textContent). Pure core: const greeting = (name, hour) => (hour < 12 ? 'Good morning, ' : 'Hello, ') + name;. Shell: document.body.textContent = greeting(document.getElementById('name').value, new Date().getHours());. You can now test greeting('Ada', 9) without a browser or a fake clock.
Exercise
A teammate writes const withIds = (items) => items.map((item) => { item.id = crypto.randomUUID(); return item; });. Name the two problems and give a fixed version.
Show answer
First, it mutates each input object (item.id = ...), so the caller's array of objects changes. Second, it depends on hidden randomness, so the output can't be predicted in tests. Fix: const withIds = (items, makeId = () => crypto.randomUUID()) => items.map((item) => ({ ...item, id: makeId() }));. In a test you can pass a counter, for example let n = 0; withIds(list, () => \id-${++n}\).
Exercise
In the checkout example, why is it acceptable to call effects.push(...) inside a function we call pure?
Show answer
The effects array is created inside the function call, and no other code can reach it until it is returned. Nothing outside the function can observe the mutation, so the function still returns the same output for the same input and causes no visible change elsewhere. Purity is judged at the function boundary.