How exactly does this recursive function work in JavaScript?

前端 未结 7 1242
伪装坚强ぢ
伪装坚强ぢ 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:45

    This line and its resolution really trips me up:

    return base * power(base, exponent - 1)
    

    I get that the exponent is decremented until it meets the base case, but when you mulitply the base times the recursive function call, I keep thinking "how does the function mulitply the base by itself(the base arguement)?", where is it doing that exactly, because calling base * power(base, exponent - 1) doesn't look like the standard loop contruction. How can it be calling a function with two arguements, how does it know to skip the exponent arguement and multiply the base by the base?

提交回复
热议问题