Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 327
Bren Avatar asked May 22 '15 00:05

Bren


1 Answers

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

like image 147
Trevor Dixon Avatar answered Oct 13 '22 00:10

Trevor Dixon