Javascript Function that validates exponent equations
javascript, recursion
Solution
The function power returns an integer, so when the function returns `base * <some_integer>` is a perfectly valid expression. The best way to trace these things is with a pen and paper:
call stack of power(2,4):
power(2, 4) = 2 * power(2, 3)
power(2, 3) = 2 * power(2, 2)
power(2, 2) = 2 * power(2, 1)
power(2, 1) = 2 * power(2, 0)
power(2, 0) = 1 <--base case
now all you have to do is substitute the values up the call stack
power(2, 4) = 2 * 8 = 16
power(2, 3) = 2 * 4 = 8
power(2, 2) = 2 * 2 = 4
power(2, 1) = 2 * 1 = 2
Problem
This is a hw assignment. The answer/output I want is correct. I just don't understand why. I want the output to be true if the power function matches the number I am checking against. I do get the answer true for these examples, but I don't understand how this recursive function is working. In the else of this function, I am saying base * the function itself. what does that even represent? How can `base * power(base, exponent - 1);` even compute? Shouldn't it just run in a circle and then finally end? ``` console.log(power(2,4) === 16); console.log(power(2,3) === 8); console.log(power(2,2) === 4); var power = function(base, exponent) { if(exponent === 0) { return 1; } else { return base * power(base, exponent - 1); } }; ```