Pure Functions and Side Effects
A pure function produces the same output for the same inputs and does not cause observable side effects. Pure functions are easier to test, cache, compose, and reason about.
Side effects are not inherently bad; applications need I/O, logging, network calls, DOM changes, and state updates. The important architectural technique is to isolate side effects from deterministic business logic where practical.
Pure vs Side-Effecting Code
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
function saveOrder(order) {
return fetch('/api/orders', {
method: 'POST',
body: JSON.stringify(order)
});
}💡 calculateTotal is deterministic for the same input and has no external effect. saveOrder interacts with the network and therefore has a side effect.
Key Takeaways
- Pure functions are deterministic and side-effect free.
- Side effects are necessary but should be controlled.
- Separating calculation from I/O improves testability.
Knowledge Check
Which function is most likely pure?