In JavaScript
there is a conception named pure function
. One of its features is that it always returns a testable result
. I am very confused with this. I'd like to know the definition and the goal and why of it.
1 Answers
A "testable result" is not a JS term. Is a physics term. When you said "Testable result" is when you make the same action and get the same result.
For example:
- If you throw a ball at the same distance it will always hit the ground at the same time
- If you drive 60km/h in 1 hour you will 60 km away.
So, in software, a testable result will be functions when you pass the same arguments you will get the same results.
For example:
cos(x)
// Allways the samemax(a,b,c)
// Allways the sameuppercase(str)
// Allways the same
Non-testable results:
random(from, to)
// Diff resultsuuid(str)
// Diff resultsgetNowTime(format)
// Diff results
Now, the concept of pure-function
is:
- Is a "testable result" (in other words: if you send the same args you will get the same result)
- Not use input or output streams
- Not use global variables (only local vars and arguments)
- Not change local static variables
- Not change any argument
In javascript examples of non-pure functions:
// Is not a testable result
function notPure(max, min) {
return Math.random() * (max - min) + min;
}
// Use output stream
function notPure(name) {
const res = "hi " + name;
console.log(res);
return res;
}
// Use global variable [This is a testable result but not pure because global variable]
const globalVar = "jett";
function notPure(lastname) {
return "hi " + globalVar + " " + lastname;
}
// In JS don't exist "local static variables" so is impossible to replicate this case
// Change an argument
function notPure(obj, key, val) {
obj[key] = val;
return obj;
}
Some examples of pure functions will be:
function pure(a, b) {
return a + b;
}
function pure(name, lastname) {
return "hi " + name + " " + lastname;
}
function pure(obj, key, val) {
const res = JSON.parse(JSON.stringify(obj));
res[key] = val;
return res;
}
In some examples, you will see "If there is an HTTP request is not a pure-function" and this is because the HTTP request
uses I/O streams and is a high possibility to get different results.
EDIT: The most important cases for pure functions is because they are "testable" so you can do unit tests without any concern and you will not get "side-effects" in your code.

- 1,024
- 7
- 25
-
1Thanks @jtwalters . It is very useful to me. :) – catcatcat Dec 31 '20 at 01:13