0

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?

9
  • If you remove the console.log from within factorial, what does it do? What effect does the line factorial(n-1); have? Commented Dec 20, 2022 at 10:24
  • main thing I would like to understand: why return is not working in "else". Whatever I write and return, it returns undifined. Commented Dec 20, 2022 at 10:34
  • The answer is that factorial(n-1); does nothing without the console.log. In the call factorial(5), there is no return, control falls off the bottom of the function Commented Dec 20, 2022 at 10:36
  • I made some edition. I am returning in the else, why function rec is not returning this value? Commented Dec 20, 2022 at 10:40
  • Because the call to rec(5) doesn't visit the else. Only the call to rec(0) does Commented Dec 20, 2022 at 10:41

1 Answer 1

1

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;
};
Sign up to request clarification or add additional context in comments.

2 Comments

I am really glad and appreciate your time. I am still a little bit confused why else return is undefined and not result value if it is in the end of the function, but I understand better how to make recursion. Thanks for your help!
@titoih the function happens multiple times, each is independent of the others. returning from the innermost function doesn't mean the outermost function returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.