0

I came across a Javascript challenge, and I could use some help understanding the inner-workings of the solution. Challenge was to find factorial of a given number.

Solution is as follows:

function FirstFactorial(num) { 

    if (num === 0 || num === 1) {
        return 1;
    }
    else {
         return num * FirstFactorial(num - 1);
    }     

 }

FirstFactorial(someInt);

I get what’s happening, I just don’t get why. The value of a function can’t be determined from an indeterminate parameter, so it first iterates through each and get the value of the parameters.

What’s confusing is why is seems to iterate backwards once the values of the parameters are determined.

This whole process is rather unclear, and I was hoping someone could explain how Javascript works under the hood in this case. Thanks!

silencedogood
  • 3,209
  • 1
  • 11
  • 36
  • this is known as **recursion**, this is not a javascript based knowledge only. You should have a read about it. Its a very great concept. – Farhan Qasim Feb 12 '19 at 15:39
  • i feel like this is gonna get dupehammered – Alan Feb 12 '19 at 15:39
  • Bummer, because I understand recursion... Just not why javascript operates in reverse after obtaining parameter values. Oh well :( – silencedogood Feb 12 '19 at 15:41
  • Expand on what you *think* is happening, and what exactly you mean by "reverse". – deceze Feb 12 '19 at 15:42
  • @deceze actually that second duplicate post is EXACTLY what I was looking for. I think I missed it because I was entering javascript as a tag, and it is a python example that explains it. Anyways, that post directly addresses the reverse order I mentioned. Thanks! And sorry for the duplicate. – silencedogood Feb 12 '19 at 15:49

0 Answers0