We are required to write a JavaScript function that takes in a number as the only argument. The function should sum the digits of the number while the sum converses to a single digit number.
For example −
If the number is −
const num = 54564567;
Then the function should sum it like this −
5+4+5+6+4+5+6+7 = 42 4+2 = 6
Therefore, the final output should be 6
Example
const num = 54564567; const sumDigits = (num, sum = 0) => { if(num){ return sumDigits(Math.floor(num / 10), sum + (num % 10)); }; return sum; } const sumDestructively = (num) => { let sum = num; while(sum > 9){ sum = sumDigits(sum); }; return sum; } console.log(sumDestructively(num));
Output
And the output in the console will be −
6