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 >=
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.