Repeated sum of Number’s digits in JavaScript


We are required to write a JavaScript function that recursively sums up the digits of a number until it reduces to a single digit number.

We are required to do so without converting the number to String or any other data type.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const num = 546767643;
const sumDigit = (num, sum = 0) => {
   if(num){
      return sumDigit(Math.floor(num / 10), sum + (num % 10));
   }
   return sum;
};
const sumRepeatedly = num => {
   while(num > 9){
      num = sumDigit(num);
   };
   return num;
};
console.log(sumRepeatedly(num));

Output

The output in the console will be −

3

Updated on: 22-Oct-2020

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements