Javascript recursive function not returning value?

You’re not returning anything inside else. It should be:

return digital_root(count);
^^^^^^^

Why?

digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don’t use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:

var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result;                    // return the result of that so it can be used from the caller of digital_root

Leave a Comment