What is a pure function?
18 September 2022 (Updated 18 September 2022)
In a nutshell
A pure function is a function with the following characteristics:
- It has no side-effects. It doesn’t change any objects or variables that existed before it was called.
- Given the same inputs, it’ll always return the same output.
Example of a pure function
function triple(number) {
return number * 3;
}
This function is pure because:
- It doesn’t change any variable or object in the outer scope.
- Given the same
number
argument, it’ll always return the same value.
Example of an impure function
let someVar = 'foo'
function triple(number) {
someVar = 'bar'
return number * 3;
}
This function is impure because:
- It causes a side-effect – mutates
someVar
which is part of the outer scope.
Another example of an impure function
const isMonday = new Date().getDay() === 1
function triple(number) {
if (isMonday) {
return number * 3 + '!!!'
}
return number * 3;
}
This function is impure because:
- Given the same
number
input, its output is unpredictable. It could be different depending on the value ofisMonday
.
Sources
Tagged:
Computing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment