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