Pure functions
suggest changeA basic principle of functional programming is that it avoids changing the application state (statelessness) and variables outside its scope (immutability).
Pure functions are functions that:
- with a given input, always return the same output
- they do not rely on any variable outside their scope
- they do not modify the state of the application (no side effects)
Let’s take a look at some examples:
Pure functions must not change any variable outside their scope
Impure function
const obj = { a: 0 }
const impure = (input) => {
// Modifies input.a
input.a = input.a + 1;
return input.a;
}
const b = impure(obj)
console.log(obj) // Logs { "a": 1 }
console.log(b) // Logs 1
The function changed the obj.a value that is outside its scope.
Pure function
const obj = { a: 0 }
const pure = (input) => {
// Does not modify obj
const output = input.a + 1;
return output;
}
const b = pure(obj)
console.log(obj) // Logs { "a": 0 }
console.log(b) // Logs 1
The function did not change the object obj values
Pure functions must not rely on variables outside their scope
Impure function
let a = 1;
const impure = (input) => {
// Multiply with variable outside function scope
const output = input * a;
return output;
}
console.log(impure(2)) // Logs 2
a++; // a becomes equal to 2
console.log(impure(2)) // Logs 4
This impure function relies on variable a that is defined outside its scope. So, if a is modified, impure’s result will be different.
Pure function
const pure = (input) => {
const a = 1;
// Multiply with variable inside function scope
const output = input * a;
return output;
}
console.log(pure(2)) // Logs 2
The pure function’s result does not rely on any variable outside its scope.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents