The sum of digits can be calculated using that function (based on other answers):
function sumDigits(n) {
let sum = 0;
while (n) {
digit = n % 10;
sum += digit;
n = (n - digit) / 10;
}
return sum;
}
If you really need to sum the digits recursively there is recursive version of the function:
function sumDigitsRecursively(n) {
let sum = sumDigits(n);
if (sum < 10)
return sum;
else
return sumDigitsRecursively(sum);
}
The sumDigitsRecursively(2568)
expression will be equal to 3
. Because 2+5+6+8 = 21
and 2+1 = 3
.
Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.