Cannot wrap my head around this recursive exponent function

Cannot wrap my head around this recursive exponent function
0

#1

I have a function named ‘recursiveExponent’ that takes two arguments, base and expo, and I am trying to recursively return the exponent value of the base. I understand the steps in using a while loop:

var exponent = function(base, expo) {
  var val = base;
  while (expo > 1) {
    val *= base;
    expo--;
  }
  return val;
}
console.log(exponent(2, 4), 'should be 16');

But, below, I cannot get how calling it again inside the function emits 16

var recursiveExp = function(base, expo) {
  // if the number is 1, return the base
  if (expo === 1) {
    return base;
  }
  // otherwise, call the recursive function again
  return base * recursiveExp(base, --expo);
  /*
  recursiveExp(2, 4)
  Each call, while expo does not equal to 1
  1st call - recursiveExp(2, 4)      2 * recursiveExp(2, 3) ???
  2nd call - recursiveExp(2, 3)     2 * recursiveExp(2, 2) ???
  3rd call - recursiveExp(2, 2)      2 * recursiveExp(2, 1) ???
  4th call - recursiveExp(2, 1)      expo is now === 1 so returns base which should be 16
  */
}
console.log(recursiveExp(2, 4), 'should be 16');

If you are wondering where I got this code, its part of the algorithms and data structure course on frontendmasters.com


#2

HI @francisngo

The thing to understand with recursion is that until the final function call actually returns a value, nothing is evaluated, so it sort of works inside out. Once the base is returned when expo === 1 it can start evaluating upwards. So if you flip the calls in your example, it might be easier to understand.

var recursiveExp = function(base, expo) {
  if (expo === 1) {
    return base;
  }
  return base * recursiveExp(base, --expo);
  /*
    4th call - recursiveExp(2, 1) = 2 (remember, at the end, all it's doing is returning the base)
    3rd call - recursiveExp(2, 2) = 2 * 2(4th call), returns 4
    2nd call - recursiveExp(2, 3) = 2 * 4(3rd call), returns 8
    1st call - recursiveExp(2, 4) = 2 * 8(2nd call), returns 16
  */
}
console.log(recursiveExp(2, 4), 'should be 16');

I hope this helps. Recursion is definitely a fickle mistress, but if you understand how it works you can write some pretty powerful and clean code.