Pure Functions: Every Developer Should Know About

Abhishek Srivas
Stackademic
Published in
4 min readJan 8, 2024

--

While surfing through the ocean of programming we generally stumble upon many icebergs (i.e. concepts) which seem very small and basic from the outside yet are huge and deep in reality, and one of them is Pure Functions.

Definition: In simple language, Pure functions are a concept in functional programming that follows these two sets of rules:

  1. Deterministic: “A pure function, given the same set of input parameters, will always produce the same output”, reading this you might have remembered that you have studied this somewhere, and if yes then you are right this concept is used in maths. And for those who didn’t remember this, we are in the same boat. f(x,y) = x + y is an example of a mathematical pure function, this function takes two inputs, x and y, and always produces the same sum for the same pair of inputs.
  2. No Side Effects: Pure functions do not have side effects, meaning they do not modify variables outside their scope, alter global states, perform I/O operations, or interact with the external world in any way beyond computing the result. The function’s only purpose is to compute and return a value based solely on its inputs.

What does a pure function look like 🤔 ?

Now let’s understand this through a simple example: In this example, the add function is pure because it takes two parameters (a and b) and returns their sum. It doesn’t modify any external state, and calling it with the same arguments will always produce the same result.

// Pure function
function add(a, b) {
return a + b;
}
console.log( add(1,1) ) // Output: 2

Compare this with an impure function that modifies a variable outside its scope:

// Variable outside functions scope
let total = 0;

// Impure function
function addToTotal(value) {
total += value;
return total;
}

The addToTotal function is impure because it modifies the total variable outside its scope, introducing a side effect (another interesting term you can look into). It becomes harder to predict the function’s behavior over time and in different contexts. Let’s take an example for those for whom it’s hard to imagine why it is a problem.

let itemPrice = 100;

// Returns price after applying offer.
function applyOffer(offerPercent){
// Updates variable outisde it's scope
itemPrice = (itemPrice*(100-offerPercent))/100;
return itemPrice;
}

console.log(applyOffer(10)); // Returns 90 for the first time
console.log(applyOffer(10)); // Returns 81 for the second time 😕
console.log(itemPrice) // Returns 81

In this example, you can clearly see why impure functions might cause problems.

Bonus Info: Do you know React is designed around this concept? React assumes that every component you write is a pure function. This means that the React components you write must always return the same JSX given the same inputs:

Making Our Impure Function Pure:

To make the applyOffer function you just saw pure, you should avoid modifying the external state and instead ensure that it only relies on its input parameters.

let itemPrice = 100;

// Added a new arg, itemPrice. NOTE: you can name it whatever you want, I have just displayed the example of variable shadowing.
function applyOffer(itemPrice,offerPercent){
// Updates variable outisde it's scope
itemPrice = (itemPrice*(100-offerPercent))/100;
return itemPrice;
}

console.log(applyOffer(itemPrice,10)); // Returns 90 for the first time
console.log(applyOffer(itemPrice,10)); // Returns 90 for the second time 😄
console.log(itemPrice) // Returns 100

Benefits of using pure functions:

  • Easy to trust, as they always give the same output on the same input.
  • Pure functions are easier to combine because their “output depends only on input”.
// Example, easier functional composition is enabled due to this
let myFavOutput = doThis(a).thenThis(b)
.andFinallyThis(c)
  • Pure functions are easier to test and debug.
  • Pure functions are memoizable ( because of it’s Deterministic nature).
  • Easier to Parallelize (read this to know more )

Each of the above advantages can be a detailed article in itself but for now, I just want you to think about why these general and obvious points have so much value and use.

Conclusion:

I believe by now you have a good understanding of what pure functions are and why this concept is so powerful. An example can be found in this React documentation on how React uses the concept of pure functions.

It’s easy to understand the concept but hard to master it.

If you like this article, you can buy me a coffee to support my work.

Buy me a Coffee ☕️

Stackademic

Thank you for reading until the end. Before you go:

--

--

By day, I'm a software developer; by night, I'm into self-growth and motivation. I like to simplify and share my learnings. Let's code and grow together! 🚀✨