Reputation: 3414
I need small help in a small code. The function is returning undefined and i want to return the console.log of the sum. The code is here http://jsbin.com/jedigigigo/edit?js,console
var addDigits = function a(num) {
var length = num.toString().length;
var value = num.toString();
var sum = 0;
for (var i = 0; i < value.length; i++) {
sum += Number(value[i]);
}
if (sum > 9) {
a(sum);
} else {
console.log(sum);
return sum;
}
};
console.log(addDigits(38));
Upvotes: 0
Views: 130
Reputation: 773
var addDigits = function a(num) {
var length=num.toString().length;
var value=num.toString();
var sum=0;
for(var i=0;i<value.length;i++) {
sum+=Number(value[i]);
}
if(sum > 9) {
return a(sum);
}
else
{
return sum;
}
};
console.log(addDigits(38));
Upvotes: 0
Reputation: 356
I have edited your code. I don't know why are calling sum recursively here. If I understood it correct then you are only trying to return sum of digits of a number (non-negative). I modified your code like below
var addDigits = function a(num) {
var length=num.toString().length;
var value=num.toString();
var sum=0;
for(var i=0;i<value.length;i++) {
sum+=Number(value[i]);
}
return sum;
};
console.log(addDigits(23456));
I updated your bin also you can check here
Upvotes: 0
Reputation: 853
Add return in if statement :-
/**
* @param {number} num
* @return {number}
*/
var addDigits = function a(num) {
var length = num.toString().length;
var value = num.toString();
var sum = 0;
for (var i = 0; i < value.length; i++) {
sum += Number(value[i]);
}
if (sum > 9) {
return a(sum);
} else {
console.log(sum);
return sum;
}
};
console.log(addDigits(38));
Upvotes: 5
Reputation: 502
if(sum>9) {
return a(sum); // You forgot to return a value from recursive call.
}
Although the code looks really weird :)
Upvotes: 4