This one good. Recursion can make your head spin. The reason it is undefined is that not all iterations return a value, and for those that you don't get undefined, itβs the same as if you set the variable to any function that does not return a value.
This gets confused with recursion because the return value that you see in this case comes from the first and last completed iteration. Unlike a regular method call, when return interrupts the method - sending it back to wherever it appears, recursion still scrolls back through the call stack, returning all the values ββit should return, including undefined, in reverse order, in which they were called. Thus, it actually gives your console.log four return values: 15, undefined, undefined, undefined.
Since it is synchronous, console.log cannot be executed until the method is processed. What it outputs is the last value it receives, or undefined. If you return after calling the method in the else block, you will see that you got 5 or the acc value after the first iteration of the function.
var multiplyT = function(a, b, acc) { if (b == 0) { console.log("BASE CASE: ", acc); return acc; } else { b--; acc = acc + a; console.log("NOT THE BASE CASE: ", a,b,acc); multiplyT(a, b, acc); return acc; } } console.log(multiplyT(5,3,0));
source share