Search code examples
javascriptrecursionfactorial

factorials... I have no idea why this code works


I came across an exercise on freecodecamp that required writing a code that would return the factorial for a given integer and gave this example: For example: 5! = 1 * 2 * 3 * 4 * 5 = 120f.

I get how the math works but I couldn't really wrap my head around how to code it until I found something here, n stackoverflow, but without an explination of why it works, that resembled this:

function factorialize(num) {
  if(num === 0) {
    return 1;
  } else {
    return num * factorialize(num - 1);
  }
}

factorialize(5);

I don't really understand how this is iterating through all the integers that are less than or equal to num. Can anybody help explain this to me?


Solution

  • It's a recursive function.

    Calling factorialize with 5 does the following:

    Is 5 equal to 0? No, so then:

    return num * factorialize(num - 1); 
    

    Substituting 5 for num means it is actually returning:

    5 * factorialize(5-1)
    

    So we can simplify that to

    5 * (factorialize(4))
    

    Which then must call factorialize on the second half of the statement to computer the return value.

    So you can imagine, factorialize is called again with num = 4. Since num is not equal to zero, it also returns the same num * factorialize(num-1). The original statement is now:

    5 * (4 * factorialize(3))
    

    and so it must call itself again... and again... until we have

    5 * 4 * 3 * 2 * 1 * factorialize(0)
    

    which then actually returns a single number - this is called a base case so it doesn't infinitely recurse on itself. It returns 1.

    Resulting in

    5 * 4 * 3 * 2 * 1 * 1
    

    I would argue the base case should be if (num == 1). Either way it works

    Edit based on comment: The 0 makes sense, it obviously now covers 0 factorial. Thanks! With the base case of num == 1 it would only work for factorialize with a parameter num > 0.