AI Hints
Home›JavaScript Tutorial›Better Functions
JavaScript · Lesson 40 of 138

Pure Functions

No side effects.

⏱ 2 min read▶ Video at 48:01🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Pure Functions
From the video: Pure Functions
  • 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.

app.jsjavascript
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));
Output
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.

keyvalue
Puresame input, same output
Side effectchanges the outside world
Easy to testjust check outputs
Goalfew 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
Next up: Function Mistakes — and how to avoid them