Functional Programming: Pure Functions

Pure Functions is part of Functional Programming that a function doesn't depend on any external resources such as global variables, other functions, any type of remote requests or anything else except The given inputs which are the function arguments.

Another key of Pure Functions that it MUST NOT have a side effect such as throwing an error, logging or calling another function that may produce such things like these.

So Pure Functions are simply function that perform certain operations on the given arguments only that will always, always return same result.

Let's see some examples to clarify it.

// js snippet code

/**
 * A pure function
 * Double the given number
 * 
 * @param   Number number
 * @returns Number
 */
function doubleNumber(number) {
    return number * 2;
}    

doubleNumber(4); // 8

So that is, we just doubled the given number without using any other resources than the given input itself.

Example of non pure function

Now let's see an example of non pure function.

// js snippet code

let multipliedBy = 3;
/**
 * A non pure function
 * Double the given number
 * 
 * @param   Number number
 * @returns Number
 */
function multiply(number) {
    return number * multipliedBy;
}    

multiply(2); // 6

// what if multipliedBy changed like this!
multipliedBy = 5;

multiply(2); // 10

In the previous case, the given argument was multiplied by a global scoped variable, which could be changed in any circumstances.

Converting the previous non pure function to pure functions

Well, the previous example could be changed to a pure function with a simple trick, which is passing the multipliedBy value as second argument.


// js snippet code

let multipliedBy = 3;

/**
 * A non pure function
 * Double the given number
 * 
 * @param   Number number
 * @param   Number number2
 * @returns Number
 */
function multiply(number, number2) {
    return number * number2;
}    

multiply(2, multipliedBy); // 6

TL;DR

So let's summarize Pure Functions Characteristics in points.

  • It doesn't have any side-effects.
  • It doesn't affect on other expressions.
  • It always returns a value.
  • It only deals with the given arguments.
  • It doesn't use any external resources such as variables, functions, I/O...etc.
  • Its value is always the same, it never changes for same input.
  • It doesn't mutate the given inputs nor any other external states.
  • Easy to cache.
  • Testable.
Programming Concepts#Programming Concepts

Comments (1)

heba taha
heba taha
6 months ago

Great post