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!