Search code examples
javascriptrecursionfunctional-programmingfactorial

Confusion with state of parameter in recursion with javascript


Gif for the debugger in console

So, when running this, i'm a bit confused how fac parameter is maintaing the state. what i understand by factorial(4) is

  1. 4 * (4-1) // 4 * 3 = 12
  2. 12 * (3-1) // 12 * 2 = 24
  3. 24 * (2-1) // 24 * 1 = 24
function factorial(fac){
  debugger
  if(fac == 1)
    return fac
  return fac * factorial(fac-1)
}
factorial(4)

Solution

  • Every call to factorial has its own fac parameter, with its own value. So when, in the first call (during factorial(4)), when you do:

    return fac * factorial(fac - 1);
    

    that calls factorial again, passing in the value resulting from fac - 1 (3). That new call receives fac = 3 and does its work with it. While that's happening, the first call is waiting to get the return value from it (let's call it retVal) so it can finish the return fac * ____________ by plugging retVal in where ____________ is.

    Eventually, a call to factorial does its work by returning fac instead of calling factorial again, which means the one that called it can complete its work and return its return value, which means the one that called it can do that, until we get back to the top one that returns the overall result.

    Here's an attempt to show how the calls stack up (using indentation for showing the recursive calls):

    factorial(fac = 4)
        factorial(fac = 3)
            factorial(fac = 2)
                factorial(fac = 1)
                return 1
                       |
                       v
            return 2 * 1 = 2
                           |
                   +−−−−−−−+
                   |
                   v
        return 3 * 2 = 6
                       |
               +−−−−−−−+
               |
               v
    return 4 * 6  = 24
    

    Note that when factorial(1) is running, there are four different fac parameters in memory, fac = 4 (the outermost call), fac = 3 (the first recursive call), fac = 2 (the next recursive call), and fac = 1 (the last recursive call before the returns kick in).