because power(base, exponent) has no return value unless exponent is 0, initially, shouldn't power(base, exponent -1) return 'undefined', and therefore be unmultipliable, initially? So, I am having trouble following the logic of this code. Why/how does it work?
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
It could be more concise:
function power(base, exponent) {
return exponent == 0? 1 : base * power(base, --exponent);
}
Howerver an iterative solution is very much faster:
function powerNR(base, exp) {
var result = 1;
while(exp--) {
result *= base;
}
return result;
}