How does using a return clause before a recursive function call differ from not using one?

前端 未结 6 375
旧时难觅i
旧时难觅i 2021-01-25 09:39

I was just experimenting with some recursion and noticed something that confused me. Let me illustrate with some code examples:

function loop(x) {
  if (x >=          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-25 10:22

    The order in which this recursive call will evaluate will be from the last call down. The function that gets evaluated first is the loop(10) which returns a value of 10. The next will be loop(9) and so on. Think about what loop(9) will look like when it is called:

    loop(9) {
        if (x >= 10) 
            return x;
        10
    }
    

    loop(9) will return undefined. loop(8) will as well... and so on.

    Conversely, if you return the value of the recursive call it would look like this:

    loop(9) {
        if (x >= 10) 
            return x;
        return 10
    }
    

    and by the time your initial function call gets executed it will look like this:

    loop(0) {
        if (x >= 10) 
            return x;
        return 10
    }
    

    I created a jsfiddle to demonstrated the point: http://jsfiddle.net/TSnxp/

提交回复
热议问题