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

coding basics if / else and return (for example in javascript)

I have been some time coding, not to much as you will see (1-2 years), but I am facing this question and I am feeling ashamed.
This is not the first time I am confused about it. I have looked in some books of other languages as Java, but I can’t solve it by myself.

Why in this script the return is undefined?

const factorial = n => {
  let result = 1;
  const rec = (n) => {
    if(n>0) {
    result = result * n;
    rec(n-1);
    } else {
    console.log(result)
    return result;
    }
  }
  return rec(n);
};

console.log(factorial(5))
120
undefined

PS: I edited to clear what I would like to understand. Why function rec is not returning result?

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

>Solution :

Your function has multiple calls. Either return from all of them, or none of them.

const factorial = n => {
  if(n>0) {
    return factorial(n-1) * n;
  } else {
    return 1;
  }
};


const factorial = n => {
  let result = 1;
  const rec = (n) => {
    if(n>0) {
      result = result * n;
      rec(n-1);
    }
  }
  rec(n);
  return result;
};

The alternative is to loop, not recurse

const factorial = n => {
  let result = 1;
  for (; n>0; n--) {
    result = result * n;
  }
  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