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:

  1. a stack of calls function created: process needs proper termination condition end (otherwise you'll have infinite recursion, evil)
  2. 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

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -