Javascript recursive function not returning value?

Javascript recursive function not returning value?

javascript recursive function not defined
recursive function not returning value python
recursive function javascript
return in recursive function
return value from recursive function python
typescript recursive function return value
javascript recursive function array
javascript recursive function return array

Im solving a codewars problem and im pretty sure i've got it working:

function digital_root(n) {
    // ...
    n = n.toString();
    if (n.length === 1) {
        return parseInt(n);
    } else {
        let count = 0;
        for (let i = 0; i < n.length; i++) {
            //console.log(parseInt(n[i]))
            count += parseInt(n[i]);
        }
        //console.log(count);
        digital_root(count);
    }
}

console.log(digital_root(942));

Essentially it's supposed to find a "digital root":

A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.

But then it jumps out of the if statement and tries to return from the main digital_root function?

Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?


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

How to save the return value of a recursive function in a variable , Your code: myFunction() will return void/ undefined on first call, it is not a recursive approach. Following example is a recursive approach. Using reduce. A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced.


Code review

My remarks is code comments below

// javascript generally uses camelCase for function names
// so this should be digitalRoot, not digital_root
function digital_root(n) {
    // variable reassignment is generally frowned upon
    // it's somewhat silly to convert a number to a string if you're just going to parse it again
    n = n.toString();
    if (n.length === 1) {
        // you should always specify a radix when using parseInt
        return parseInt(n);
    } else {
        let count = 0;
        for (let i = 0; i < n.length; i++) {
            //console.log(parseInt(n[i]))
            count += parseInt(n[i]);
        }
        // why are you looping above but then using recursion here?
        // missing return keyword below
        digital_root(count);
    }
}

console.log(digital_root(942));

Simple recursive solution

With some of those things in mind, let's simplify our approach to digitalRoot...

const digitalRoot = n =>
  n < 10 ? n : digitalRoot(n % 10 + digitalRoot((n - n % 10) / 10))
  
console.log(digitalRoot(123))         //          => 6
console.log(digitalRoot(1234))        //       10 => 1
console.log(digitalRoot(12345))       //       15 => 6
console.log(digitalRoot(123456))      //       21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9

JavaScript Recursive Function By Example, The recurse() is a recursive function if it calls itself inside its body, like this: Uncaught TypeError: countDown is not a function function sumOfDigits(num) { if (num == 0) { return 0; } return num % 10 + sumOfDigits(Math.floor(num / 10)); } Reduce an Array Into a Value: reduce() � Transform Array Elements: map() � Loop� JavaScript recursive function examples. Let’s take some examples of using the recursive functions. 1) A simple JavaScript recursive function example. Suppose that you need to develop a function that counts down from a specified number to 1. For example, to count down from 10 to 1:


its a recursive function the code should be somewhat like this

function digital_root(n) {
    // ...
    n=n.toString();
    if(n.length === 1){
         return parseInt(n);
    }
    else
    {
    let count = 0;
    for(let i = 0; i<n.length;i++)
    {
    //console.log(parseInt(n[i]))
    count+=parseInt(n[i]);
    }
   //console.log(count);
   return digital_root(count);
   }
}

you should return the same function instead of just calling it to get the correct call stack

Recursion and stack, The variables are same, but the line changes, so the context is now: There are no more nested calls, so the function finishes, returning 2 . Recursion is a programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways. When a function calls itself, that’s called a recursion step. The basis of recursion is function arguments that make the task so simple that the function does not make further calls.


Recursive function logic works but in one case the returned value is , Recursive function logic works but in one case the returned value is wrong?! Curriculum Help JavaScript � thecalicoder April 10, 2018, ways may perform better. The problem is that you're not returning when you ought to be. This is a function that returns the value of multiplying a number again and again by each preceding integer, all the way down to one. JavaScript recursive functions need to keep track of where


Recursive function is returning "undefined" : javascript, I have a recursive function that seems to be returning undefined even though console.log indicates that the though console.log indicates that the return statement in the function should have a value. You're not returning your recursive call. When you call the function recursively here, your second iteration will return a value to this calling line when it finds the zero value. At that point, you need to return that value to the first


Recursion in JavaScript — Call a smaller version of you, Although Javascript doesn't have a solid tail call optimization, recursion is condition that causes the function to return a value instead of calling itself again. However a recursive function does not return immediately. Recursive function is returning "undefined" help I have a recursive function that seems to be returning undefined even though console.log indicates that the return statement in the function should have a value.