ilyo - 10 months ago 45

Javascript Question

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?

Answer Source

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

- 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**) - 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 :)