Pure Functions
No side effects.
Some functions are completely predictable. Give them the same input, and they always give the same output, without changing anything else. They're called pure functions, and they're the easiest code to trust.

- Same input, same output
- Changes nothing else
- Pure functions
Pure and impure
Add tax is pure. It only uses its inputs, and returns a result. Add to total is impure. It changes a variable outside itself, so calling it twice gives different results. That's called a side effect. Run it.
const addTax = (price) => price * 1.2;
let total = 0;
function addToTotal(price) {
total += price;
return total;
}
console.log(addTax(10), addTax(10));
console.log(addToTotal(10), addToTotal(10));12 12 10 20
Why prefer pure functions?
Pure functions are easy to test, because you just check the output. They're easy to reuse, and they never surprise you. Of course, programs need some side effects, like printing, saving files, or updating a page. The trick is to keep them in a few clear places, and keep the rest pure.
| key | value |
|---|---|
| Pure | same input, same output |
| Side effect | changes the outside world |
| Easy to test | just check outputs |
| Goal | few side effects, in clear places |
Summary
A pure function depends only on its inputs, and changes nothing outside. Prefer them where you can. Next, common mistakes with functions.
Key takeaways- Same input, same output
- No side effects
- Easy to test