1

So I know this is likely a duplicate, but I have not been able to figure out how to fix my problem after looking through various answers on what seems like the same topic for over an hour.

This function pulls apart the digits in a number, adds them together, and if the resulting number has more than one digit, recursively sens the resulting number back into the function for processing. My return statement is giving me "undefined" and I am not sure why. If it is defined in the if statement, which it is, I do not understand why it would not be so in the else statement:

function digital_root(n) {
  var numArray = n.toString().split('');
  var accumulator = 0;
  for(var i = 0; i < numArray.length; i++){
      accumulator += parseInt(numArray[i]);
  }
  if(accumulator >= 10){
    digital_root(accumulator);
  }
  else{return accumulator};

};

digital_root(942);//should be 6, after 15 is passed back into digital_root()
// but output is undefined.

1 Answer 1

3

You need to return the result of your recursive call, otherwise it can't propagate up the stack. Also your last else is extraneous.

function digital_root(n) {
  var numArray = n.toString().split('');
  var accumulator = 0;
  for(var i = 0; i < numArray.length; i++){
      accumulator += parseInt(numArray[i]);
  }
  if(accumulator >= 10){
    return digital_root(accumulator);
  }
  return accumulator;

};

digital_root(942);//ta-daaaa
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the concise answer, just what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.