Question about calculating the factorial of a number

Hello everyone,

I finished the CodeCademy’s JS course a while ago; I am trying to practice by solving challenges on codewars and came across this solution on calculating a number’s factorial:

function factorial(n) {
  if (n < 0 || n > 12)
    throw new RangeError();
  return n <= 1 ? 1 : n * factorial(n - 1);
}

While I see what is happening at with the exception, I have a question on the second statement return n <= 1 ? 1 : n * factorial(n - 1);. Is this a loop? And, how come it is using the function inside of itself?

I came up with the following:

function factorial(n)
{
//Return 1 when n is 0
if(n === 0){
return 1;
}
//Throw a RangeError exception when input is below 0 or above 12
else if (n < 0 || n > 12) {
throw 'RangeError'
}
//Calculate factorial
else {
let arrFactorial = []
for (i = n; i >= 1; i--){
let num = i
arrFactorial.push(num)
}
return arrFactorial.reduce(function(a, b){
 return a * b;
}, 1) 
}
}

I hope someone can explain. Thanks!

google: mdn ternary operator

It’s calling itself with a smaller subset of the problem. If the problem always gets smaller then eventually it’ll reach a trivial problem that a solution can immediately be supplied for. After that the subsets can be put together.
This makes more sense if you stop trying to picture it as a whole and instead consider what happens at each level of it.

Example: to list all files in a directory: for each subdirectory, list the files (subproblem), and for each file in this immediate directory, list those too (trivial)

Simpler example yet:

To eat a bag of candy:
if empty, stop <- trivial
eat a candy <- make the problem smaller
then eat the rest using the same strategy <- solve the subproblem

Got it. I am going to pick your brain a bit more, though:

Let’s say n is 4
4 * (4-1) = 12,
Where are we telling the function that n is now 12, to be multiplied by 2?

Bear with me, please; I am trying to solidify my understanding of the concept in order to apply it at a later time

If you don’t see n = .. then that isn’t happening.

You might want to consider how one sends a value to a function and how that function is then able look at that value. As an example you might make a function named add taking two values and returning the sum of them. This function would have to look at the values given to it.

If you have a function that can compute a factorial, then you can call it with some input and get the answer back. Then you’re free to do whatever you want with the answer, like multiplying it with another number to get the next factorial.

I think I understand how it works, but I would have to see it implemented in a different way. Thanks for your patience!