Sub topic 5
Managing Side Effects
This chapter assumes you know what a pure function is from the previous chapter. You should also be comfortable with arrow functions, default parameters, destructuring, and Array.prototype.reduce. Every example runs in Node.js.
What Counts as a Side Effect
A side effect is anything a function does besides computing its return value. It can also be anything the function reads from outside its arguments. Common examples:
- Writing output:
console.log, the DOM, files, network requests. - Reading changing input:
Date.now(),Math.random(),process.env, user input. - Mutating state: changing a global variable, an argument, or a shared object.
- Throwing exceptions that other code must catch.
A program with no side effects does nothing useful, so the goal is not to remove them. The goal is to push them to the edges of your program, where they are few, visible, and easy to replace in tests.
A Function That Mixes Everything
function checkoutImpure(cart) {
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const receipt = `Total: ${total.toFixed(2)} at ${new Date().toISOString()}`;
console.log(receipt); // effect: output
cart.length = 0; // effect: mutates the caller's array
return total;
}
const myCart = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }];
checkoutImpure(myCart);
console.log(myCart.length); // 0, the caller's data is goneThis function is hard to test for three reasons. The timestamp changes on every run, the log goes straight to the console, and the caller's array is emptied without warning.
Functional Core, Imperative Shell
A common way to fix this is to split the code in two. The functional core is made of pure functions that do the calculations. The imperative shell is a thin outer layer that gathers inputs, calls the core, and performs the effects.
// Functional core: pure, deterministic
const cartTotal = (cart) =>
cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const formatReceipt = (total, timestamp) =>
`Total: ${total.toFixed(2)} at ${timestamp}`;
// Imperative shell: effects are injected, with real defaults
function checkout(
cart,
{ now = () => new Date().toISOString(), log = console.log } = {}
) {
const total = cartTotal(cart);
log(formatReceipt(total, now()));
return { total, cart: [] }; // return a new empty cart instead of mutating
}
// Production call
checkout([{ price: 10, qty: 2 }]);
// Test call: fixed time, captured output
const lines = [];
const result = checkout([{ price: 10, qty: 2 }, { price: 5, qty: 1 }], {
now: () => '2026-01-01T00:00:00.000Z',
log: (msg) => lines.push(msg)
});
console.log(result.total); // 25
console.log(lines[0]); // Total: 25.00 at 2026-01-01T00:00:00.000ZPassing now and log in as parameters is called dependency injection. The real behavior stays the default. Tests swap in fakes and need no mocking library.
Common Mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Logging or fetching inside a `map` callback | Effects run once per element and the order is easy to miss | Compute with `map`, then loop over the results to perform effects |
| Calling `Date.now()` deep in logic | Results can't be repeated, so tests become flaky | Pass the time in as an argument |
| Mutating an argument | The caller's data changes without warning | Return a new value |
| Reading a global config | The function's real inputs are hidden | Make the config a parameter |
Exercise
Refactor const rollDie = () => Math.floor(Math.random() * 6) + 1; so the logic can be tested with a predictable result, while normal calls still behave randomly.
Show answer
Inject the randomness: const rollDie = (random = Math.random) => Math.floor(random() * 6) + 1;. In tests, call rollDie(() => 0) to get 1, or rollDie(() => 0.99) to get 6. Plain rollDie() still uses Math.random.
Exercise
Why is items.map((x) => { save(x); return x.id; }) considered poor style, even though it works?
Show answer
map signals a pure transformation, so a reader won't expect the hidden save call. The effect also runs once per element in the middle of the calculation. Separate the two steps: const ids = items.map((x) => x.id); and then items.forEach(save); (or a for...of loop) in the shell.