Javascript Recursion -> what does the return trace look like?

javascript, recursion

Solution

The `sum` is accumulated and passed forward in each call to `sumDigits`. It's this value that's returned whenever the first argument equals `0`. I find that it helps to write out the recursion explicitly:

sumDigits(123, 0);
    return sumDigits(12, 3);
        return sumDigits(1, 5)
            return sumDigits(0, 6) // the base case (sum = 6)
                return sum;

The final call returns `6`. The previous call returns the result of the final call. The call before that returns the call before the final call (and so on). So they all end up unraveling the final `sum`.

Note that each call returns the result of the next call in the chain. What stops this is the base case (i.e. a condition that results in the return of a concrete value (i.e. no additional calls)).

Problem

So, I'm just starting to explore recursion and am a little stuck on a concept. Here is a solution I located for a sum digits function ( f(126) = 1 + 2 + 6 = 9 ): ``` function sumDigits(num, sum){ if (num === 0) { return sum; } else { sum += num % 10; num = Math.floor(num / 10); return sumDigits(num, sum); }} ``` I traced it down to the base, so far everything makes sense: ``` **Trace** f(126, 0) { sum = 6 num = 12 f(12, 6) } f(12, 6) { sum = 8 num = 1 f(1, 8) } f(1, 8) { sum = 9 num = 0 f(0, 9) } f(0, 9) = 9 ``` I guess what doesn't make sense to me is HOW the base case is being passed back through during unwinding? How exactly is it traveling? I'm expecting a facepalm, but until I understand I don't think I could replicate this solution. Thanks for your help!

Original source