1

This is a basic exponent function using recursive way. I do understand how recursive works but I am having trouble seeing how this returns the base by returning the function itself

function exponent(b,n){
    if(n == 0){
        return 1;
    }else if(n == 1){
        return b;
    }
    return exponent(b,n-1);
    // return b*exponent(b,n-1);
}

console.log(exponent(7,2));  //7

I commented out the real output because I was trying to see what exponent(b,n-1) means and I don't really understand is how does returning exponent(b,n-1) will give out the base as the result?

Dora
  • 5,050
  • 9
  • 37
  • 75
  • Possible duplicate of [Calling a javascript function recursively](http://stackoverflow.com/questions/7065120/calling-a-javascript-function-recursively) – Medet Tleukabiluly Feb 16 '16 at 19:52
  • The case `n == 1` is just superflous. You could easily add another `else if (n == 2) { return b*b; }`, or you could (and should) omit them both. – Bergi Feb 16 '16 at 21:09

1 Answers1

2

Recursion is a process when the function calls itself.

The special conditions in the beginning, n == 0 and n == 1, break the infinite chain of self calls, so once n reduces to 1 or 0, the function stops calling itself.

So for exponent(7,2) it is:

  1. n == 2, return 7*exponent(7,1)
  2. n == 1, return 7

And if we combine the results it will be exponent(7,2) = 7*exponent(7,1) = 7*7 = 49.

Boris Serebrov
  • 13,820
  • 1
  • 32
  • 49
  • 1
    oh ya! omg I just wasn't seeing it clearly. Thanks thanks. Really need to start thinking it this way. – Dora Feb 16 '16 at 20:00