Javascript – Is a function getting a value from another function considered pure

functional programmingfunctionsjavascript

I'm trying to figure out a way to handle default variable values when making functions without side effects and have ended up with the following:

function getDefaultSeparator() {
    return ':';
}

function process(input, separator) {
    var separator = separator || getDefaultSeparator();

    // Use separator in some logic

    return output;
}

The default separator will be used in other functions and I only want to define it in one place.

If this is a pure function, what is the difference from just using a global DEFAULT_SEPARATOR constant instead?

Best Answer

Is a function getting a value from another function considered pure?

That depends on what the other function does, and what the calling function does. Impurity is infectious, purity isn't.

Calling a pure function doesn't change the purity of the calling function. Calling an impure function automatically makes the calling function impure also.

So, in your example, it depends on the purity of the part you left out: if that is pure, then the whole function is pure.

If this is a pure function, what is the difference from just using a global DEFAULT_SEPARATOR constant instead?

Nothing. A function that always returns the same value is indistinguishable from a constant. In fact, that is exactly how constants are modeled in λ-calculus.