Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does this recursive function work in JavaScript?

I have the following example of a recursive function, and what I don't understand is the order in which things are happening:

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

When does the function return the values, at the end of all the process or each time?

like image 288
ilyo Avatar asked Nov 28 '22 22:11

ilyo


2 Answers

A simple way to visualize what happens in recursion in general is this:

  1. a stack of calls to the function is created: this process needs a proper termination condition to end (otherwise you'll have infinite recursion, which is evil)
  2. the single results are popped out of the stack: each result is used to calculate the next step, until the stack is empty

I.e. if base=5 and exponent=3, the call stack is (last element on top):

5*(5*(5*1))
5*(5*(5*power(5, 0)))
5*(5*power(5, 1))
5*power(5, 2)
power(5, 3)

then every called function has real parameters and is ready to return a value (first element on top):

5*(5*(5*1))
5*(5*5)
5*25
125

Note that here the functions are calulated in inverse order: first power(5, 0), then power(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).

Hope it helps :)

like image 186
ascanio Avatar answered Nov 30 '22 12:11

ascanio


It is generally helpful in understanding recursive functions such as this to work things out like you would in an algebra class. Consider:

power(3, 4) 
= 3 * power(3, 3)
= 3 * (3 * power(3, 2))
= 3 * (3 * (3 * power(3, 1)))
= 3 * (3 * (3 * (3 * power(3, 0))))
= 3 * (3 * (3 * (3 * 1)))
= 3 * (3 * (3 * 3))
...
= 81
like image 40
Ray Toal Avatar answered Nov 30 '22 10:11

Ray Toal