What is a Pure Function?

What is a Pure Function?

Ferenc Almasi β€’ 2020 November 10 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

To consider a function as pure, it must meet two criteria:

  • First, it should always return the same output given the same input.
  • The function should not cause any side effects outside of its scope.

Side effects means, it doesn't alter data outside of their scope. Take the following as an example:

Copied to clipboard!
// This function is pure
// Given the input is 2, 2, the output will always be 4
const sum = (a, b) => a + b;
pure.js

In the example above, the function is pure. No matter what, if you give it the same inputs over and over again, it will produce the same output. It is deterministic. Now let's take a look at an impure function.

Copied to clipboard!
// This function is not pure
// It will give different results even if the inputs are the same
const rand = (a, b) => Math.random() * (a - b);
impure.js

In the example above, the function is impure. Even if you give it the same input multiple times, it is highly likely it will produce a different output. Also note that if a function doesn't have a return value, it is also considered to be impure.


The advantage of pure functions is that they can be easily covered by unit tests since they are deterministic. However, your goal shouldn't be to make everything pure. For example, you can have network requests that can return different values. These are also impure. Your goal should be about being deliberate about why and when side effects can occur.

What is a pure function in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

If you would like to learn more about functional programming, make sure you check out the article below.

Why Do You Need to Know About Functional Programming?
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.