Factorial challenge

Hi, so I was practising the 3 challenges for loops and arrays at the end of Javascript part I.
When I faced the factorial challenge, I did a search for a solution to calculate the factorial.

I’ve found a function expression that solves it, but I couldn’t figure out what exactly was going on.
The expression is:

const factorial = function fac(n) {return n < 2 ? 1 : n * fac(n - 1);

I understand that first it checks if the given argument is less than 2, so it would return 1, and if not it calculates the factorial.

I didn’t get the placeholder “fac(n)”, I know could be any other name like “factorial(x)”, but couldn’t understand how javascript is calculating the result exactly, can someone clarify?

Hello, @efc.

If you’ve not yet studied recursion, this solution will be more difficult to understand. If you stay the course, you’ll get to recursion, and the code you posted will make sense.

In a nutshell, recursion is calling a function from within itself. Doing so builds a ‘call stack’ where each function call is waiting for the result of the subsequent function call to be returned.

In the code you posted, a function fac is defined which takes a parameter, n. If n < 2 then 1 is returned. Otherwise the result of multiplying n by the return value of calling the same function, fac on 1 less than n is returned.

Here’s essentially the same function using if...else rather than the ternary expression with a couple of console.log() statements added to help illustrate.

function fac(n){ if(n < 2){ console.log(`${n} is less than 2, so returning 1`) return 1; } console.log(`returning result of ${n} * fac(n - 1)`) return n * fac(n - 1); }; console.log(fac(4)); //same function written with ES6's concise body arrow function syntax const fac2 = n => n < 2 ? 1 : n * fac2(n - 1); console.log(fac2(4));

I wouldn’t get too caught up in understanding recursion just yet. It will come in time.

Thank you so much for taking your time to answer me, it was a really clear and helpful answer. I was worried that I was missing something, if I didn’t learn it yet that’s fine, I will solve it using a loop for now.


1 Like

Recursion is really cool once you get there. Happy coding!

1 Like

There is one assumption that goes with that expression… n is not negative. 0! and 1! are both 1, but there is no solution for a negative n.

Something else of note in the above expression, the named function, something we would rarely see unless the function is recursive.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.