Search code examples
javascriptrecursionlogicreturn-valueexponential

Recursive power function: Why does this work if there's no initial return value?


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);
}

Solution

  • 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;
    }