recursion - How exactly does this recursive function work in JavaScript? -
i have following example of recursive function, , don't understand order in things happening:
function power(base, exponent) { if (exponent == 0) return 1; else return base * power(base, exponent - 1); }
when function return values, @ end of process or each time?
a simple way visualize happens in recursion in general this:
- a stack of calls function created: process needs proper termination condition end (otherwise you'll have infinite recursion, evil)
- the single results popped out of stack: each result used calculate next step, until stack empty
i.e. if base=5 , exponent=3, call stack (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 , ready return value (first element on top):
5*(5*(5*1)) 5*(5*5) 5*25 125
note here functions calulated in inverse order: first power(5, 0)
, power(5, 1)
, , on.. after each calulation element of stack released (i.e. memory freed).
hope helps :)
Comments
Post a Comment