0

Each time when i run this code I get the output but with that output I also get undefined What does that undefined indicates

function factorial(num) {

  let final = 1;

  function helper(no) {
    if (no === 0) return;
    if (no > 1) {
      final *= no;
    }
    no--;
    helper(no);
  }
  helper(num);
  console.log(final);
}

factorial(5)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
sagar
  • 79
  • 3
  • 8

1 Answers1

0

Your factorial function doesn't return anything indeed.

You are doing a console.log to print the value, and the absence of "return" at the end is equivalent to having an implicit return undefined.

Your browser's console will output the return value of the function, that's why you may have been confused.

Use return final instead of (or in addition to) your console.log(final);

That would be preferred if you want your factorial function to actually return a value (that you could use later) instead of just printing it to the console.

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • Hey downvoters, indeed the answer was very wrong first, but I was editing it. Please see edit ;) thank you. – Pac0 Jan 09 '19 at 10:20
  • The `helper` function is being recursively called and it modifies the external value `final`, when it's finished it simply stops executing and this modifying `final`. A `return` statement (other to than to stop the execution)` is unneeded in this case. Although I agree that it's probably a good idea to have the recursive function be pure. – VLAZ Jan 09 '19 at 10:22
  • exactly. However, the factorial function is probably missing a return anyway. OP is probably just confused with the notion of return value of a function VS printing. – Pac0 Jan 09 '19 at 10:28
  • Ah, sorry - I misread what you said. For some reason, I thought you were suggesting adding a `return` because without it the function doesn't work. – VLAZ Jan 09 '19 at 10:29