DataMiner - 1 year ago 105

Javascript Question

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

`var gcd = function(a, b) {`

if ( ! b) {

return a;

}

return gcd(b, a % b);

};

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**