What is the Pure Function

Function

function has special rules:

  1. It must work for every possible input value
  2. And it has only one relationship for each input value

Although each input will only have one output, but for different inputs may have the same output.

Pure function

Given all these, pure functions have a big set of advantages. They are easier to read and understand, as they do one thing. There is no need to look outside the function code and check for variables. There is no need to think how changing the value of the variable will affect other functions. No mutations in other functions will affect the result of the pure function for a specific input.
Pure functions are easier to test, as all dependencies are in the function definition and they do one thing.
For Example:

1
2
3
4
5
6
7
8
9
10
var arr = [1, 2, 3]

// Pure
arr.slice(0, 2) // [1, 2]
arr.slice(0, 2) // [1, 2]
arr.slice(2, 3) // [3]

// Impure
arr.splice(0, 2) // [1, 2]
arr.splice(0, 2) // [3]

Another Example:

1
2
3
4
5
6
7
8
9
10
11
// Impure
var sign = 3

// The return value depends on the system status
var isBigger = (num) => num > 3

// Pure
var isBigger = (num) => {
var sign = 3
return num > sign
}