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
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

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.