Search code examples
javascriptgreatest-common-divisor

Calling function name inside function


There are some concept I still cannot figure out in Javascript. Like this one for example. I came across this code while searching for a function to return the greatest common divisor of two integers. I tested it but I can't understand how this returns the gcd. Please can explain anyone who understand explain what does return gcd(b, a % b); do here?

    var gcd = function(a, b) {
    if ( ! b) {
        return a;
    }
    return gcd(b, a % b);
};

Solution

  • You are using a recusion, which is a pattern of calling the same function again with different paramters until an exit condition is found and then the recursion stops.

    // exit condition
    if (!b) {
        return a;
    }
    

    In this case the function is called again with moved parameter b as a and a new parameter of b with a modulo b.

    // call function again with different parameters
    return gcd(b, a % b);