# Code Wars challenge question

Trying to do the digitalroot code wars challenge, where you add the digits of a number together until it is down to a single digit number.
My code returns an “undefined” even though the console.log(n) commands shows the correct value for the variable. Any pointers would be appreciated. Thanks much!

``````// add the digits of the numbers together, return the final sum
function digital_root(n) {
console.log(n);
if (n <= 9)
return n;
else{
// use recursion!
var numString = n.toString();
var stringArr = numString.split('');
var toNums = stringArr.map((e)=> parseInt(e));
var sumNums = toNums.reduce((acc, curr) => acc + curr );
digital_root(sumNums);
}
}

console.log(digital_root(16));``````

Where’s your return for the function?

``````// add the digits of the numbers together, return the final sum
function digital_root(n) {
console.log(n);
if (n <= 9)
return n;
else{
// use recursion!
var numString = n.toString();
var stringArr = numString.split('');
var toNums = stringArr.map((e)=> parseInt(e));
var sumNums = toNums.reduce((acc, curr) => acc + curr );
// digital_root(sumNums);
return sumNums;
}
}
``````

4th line down from top of function.

``````function digital_root(n) {
return n <= 9 ? n : digital_root(n.toString().split('').reduce((acc, curr) => acc + parseInt(curr),0));
}
``````

Oh I see what you mean… add all the digits until it goes down to a single digit.

``````return digital_root(sumNums);
``````

Oh my gosh, just missing a “return” word. Frustrating. Now I just have to peel the keys out of my forehead. Thanks so much, Owel. And than you too, Dawson, for responding. Tight, concise answer.

All I really did was remove the extra map from your original solution and use the ternary operator to squeeze a little more space out. All map and filter statements can be rewritten with reduce statements.

Without recursion:

``````function digital_root(n) {
while (n > 9)
n = n.toString().split('').reduce((acc, curr) => acc + parseInt(curr),0);
return n;
}
``````