Search code examples
javascriptgreatest-common-divisor

why this javscript code giving undefined as a result? (Calculating GCD), I don't know why it's not entering if block


I don't know why its not entering if block.Maybe because of type coercion. Please correct me and tell me what's the mistake in this code.

function calculateGCD(a, b) {
  if (b === 0) {
    return a;
  } else
    console.log(a, b);
  a > b ? calculateGCD(b, (a % b)) : calculateGCD(a, (b % a));
}

function main() {
  let n1, n2, gcd;
  n1 = +prompt("enter 1st number?");
  n2 = +prompt("enter second number?");

  gcd = calculateGCD(n1, n2);

  document.write(gcd);
}


main();


Solution

  • In the function you should return the result.

        function calculateGCD(a, b) {
          let result
          if (b === 0) {
            return a;
          } else {
           console.log(a, b);
           a > b ? result = (b, (a % b)) : result = (a, (b % a));
        }
       return result
      }