How exactly does this recursive function work in JavaScript?

前端 未结 7 1253
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 19:27

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)         


        
7条回答
  •  臣服心动
    2020-12-10 19:36

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

提交回复
热议问题