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

前端 未结 6 457
旧时难觅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:05

    A function only returns the value to its immediate caller. Since in case of loop(0), the if condition is not fulfilled, return x; is not executed and the function has no other return statement, it does not return anything.

    If you'd call it with loop(10) it would fulfill the condition and return 10.

    In the second case, return loop(x + 1); causes loop to return whatever the other call to loop returns.

    Maybe it's easier to understand with a non-recursive example:

    function bar() {
        return 42;
    }
    
    function foo1() {
        bar();
    }
    
    function foo2() {
        return bar();
    }
    
    //
    foo1(); // undefined
    foo2(); // 42
    

    foo1 calls bar, but it does not do anything with the return value. Since there is no return statement inside foo, the function does not return anything.

    foo2 on the other hand returns the return value of bar.

提交回复
热议问题