Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading