Quick run through on what pure and impure functions are.

I am looking at adapting one of my current old school MVC project to use Redux for state management. Since Redux makes use of the concept of pure functions, I thought I would lay it down here.

Pure Function

Definition

A function is considered pure if:

a) It always returns the same value when given the same arguments
b) It does not modify anything (arguments, state, database, I/O, ..)

Examples of Pure Functions (in JavaScript)

1
2
3
function add(x, y) {
return x + y;
}
1
2
3
function getLength(array) {
return array.length;
}

Impure Function

Definition

A function is considered impure if it is not pure (!), typically because:

a) it makes use of an external or random value. (It stops being entirely contained and predictable)
b) It performs an external operation, in other words it causes side effects

Examples

1
2
3
4
5
var x = 5;
function addToX(a) {
return a + x; // Use of an external variable
}
1
2
3
function getTime() {
return new Date().getTime(); // Use of a random/non consistent value
}
1
2
3
4
function add(x,y) {
updateDatabase(); // Side Effect
return x + y;
}

The Big Deal

The reason why Pure Function are great:

Predictable

Yep, I know, it’s part of the definition, but using a function and knowing exactly what it does feels so good.

Portable

Pure functions can be reused easily as they do not hold any form of state.

Cacheable

Since the result will always be the same, it becomes easy to cache results.

Testable !

Last but not least, pure functions are easy and a pleasure to test with automated tests.