1

The following javascript function only returns undefined

function digital_root(n) {
  var x = String(n).split('');
  if (x.length > 1) {
    sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0);
    digital_root(sum);
  } else {
    console.log(x);
    return x;
  }
}

however it prints the correct value when run in node. So why does it return undefined?

> digital_root(12)
[ '3' ]
undefined

If I take the console.log(x) statement out, the function still returns undefined

> digital_root(12)
undefined
2
  • 1
    wheres the return statement in the if true branch? Commented Apr 14, 2021 at 16:24
  • @MarianTheisen You were correct, that was the issue. I didn't realize I needed a return statement there as well. Commented Apr 14, 2021 at 16:25

2 Answers 2

1

The first time your function runs it goes into the if block, where it calls itself again with argument digital_root(3).

This "inner" call is processed first now, this time going into the else block, where the console.log(x) call happens and then return ['3'] explicitly returns that value to the outer function call, so that return value is not shown on the console.

After the inner call returned the value, the outer function terminates, because there's nothing left to do, so the outer function never returns anything.

Functions do have a default return value of undefined whenever there is not explicit return statement.

Sign up to request clarification or add additional context in comments.

1 Comment

If I take the console.log(x) statement out, the function still only returns undefined. However, I know that x should be returned since it was able to printed. Or am I misunderstanding something fundamental?
0

I figured it out. I needed to include return for the recursive call.

The full code should look like this

function digital_root(n) {
  var x = String(n).split('');
  if (x.length > 1) {
    sum = x.reduce((accumulator, value) => parseInt(value) + accumulator, 0);
    return digital_root(sum);
  } else {
    console.log(x);
    return x;
  }
}

Comments

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.