Reputation: 142
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
Upvotes: 1
Views: 58
Reputation: 56720
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.
Upvotes: 1
Reputation: 142
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;
}
}
Upvotes: 0