Why would a return be undefined but console.log return an int?

Bren picture Bren · May 22, 2015 · Viewed 7.9k times · Source

So I have the following 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);
    }

}

It gets called with:

console.log(multiplyT(5,3,0));

And gives this:

NOT THE BASE CASE:  5 2 5
NOT THE BASE CASE:  5 1 10
NOT THE BASE CASE:  5 0 15
BASE CASE:  15
undefined

As output. What I am confused about is why acc would give the correct value for the console.log but be "undefined" according to what is returned.

Answer

Trevor Dixon picture Trevor Dixon · May 22, 2015

In your else block, it should be return multiplyT(a, b, acc);