Greatest Common Divisor Algorithm

I am writing an algorithm to determine the greatest common divisor of two integers.

function gcd(a,b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a%b);
  }
}    
gcd(1,5);

This function starts to work. b does equal 0 after the second iteration. At that point, a is equal to 1, and that is the answer we expected. The problem is that it iterates once more and b becomes undefined. a also becomes undefined. When I console.log(a) in the if b==0 conditional, I get two values for a. The first is 1, the second is undefined. If b == 0, we should return a and the function should end. Why am I getting undefined here?

Can you specify which inputs yield undefined?

Also it’s best to use === when comparing with 0.