Home > OS >  why this javscript code giving undefined as a result? (Calculating GCD), I don't know why it�
why this javscript code giving undefined as a result? (Calculating GCD), I don't know why it�

Time:12-19

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

CodePudding user response:

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
  }
  • Related