pure-function

About ' testable result ' in pure function


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.


Solution

  • 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:

    So, in software, a testable result will be functions when you pass the same arguments you will get the same results.

    For example:

    Non-testable results:

    Now, the concept of pure-function is:

    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.