How to call a JavaScript function recursively

How to call a JavaScript function recursively

2017, Jan 12    

Situation

So I have developed math.js, a small npm-package (still WIP), which contains very simple functions, in a format like below:

greatestCommonDivisor: function (x, y) {
    var remainder = x % y;
    if (remainder === 0) {
        return y;
    }

    return greatestCommonDivisor(y, remainder);
}

Running the tests after having added the fore-mentioned function, wasn’t as fun as I thought, though: Tests failed

Solution

Hopefully, js already provides a feature with the help of which we can work around situations where we need to reference the function inside itself, so, we need to somehow provide a naming to the function itself. This is called a named function expression:

 greatestCommonDivisor: function gcd(x, y) {
    var remainder = x % y;
    if (remainder === 0) {
        return y;
    }

    return gcd(y, remainder);
}

Tadaaam! Tests turned green again, after this slight change. Let’s commit!

Closing Quote

You already know where you’re good at, but how sure could you be about things you never tried before?