How exactly does this recursive function work in JavaScript?

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

    The key here is that power is calling itself exactly in the way it could call any other function. So when it does that, it waits for the function to return and uses its return value.

    So if you do

    var x = power(10, 2);
    
    1. Your call to power will get to this line:

      return base * power(base, exponent - 1)
      

      ...and call power(10, 1), waiting for that to return.

    2. The call to power(10, 1) will, of course, get to the line:

      return base * power(base, exponent - 1)
      

      ...and call power(10, 0), waiting for that to return.

    3. The call to power(10, 0) will return 1, which is then used by the call in #2 above to complete its work and return 10 * 1 = 10, which will then let your original call in #1 above return the value 10 * 10 = 100.

    When seeking to understand things like this, there's nothing quite like walking through the code with a debugger. In this modern world, you have plenty to choose from, many of which may already be on your computer.

提交回复
热议问题