简体   繁体   中英

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);
};

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM