Sum up a number until it becomes 1 digit JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a Number as the only input. The function should do one simple thing −

  • keep adding the resultant digits until they converse to a single digit number.

For example −

const num = 5798;

i.e.

5 + 7 + 9 + 8 = 29
2 + 9 = 11
1 + 1 = 2

Hence, the output should be 2

Example

The code for this will be −

const num = 5798;
const sumDigits = (num, sum = 0) => {
   if(num){
      return sumDigits(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const repeatSum = (num) => {
   if(num > 9){
      return repeatSum(sumDigits(num));
   };
   return num;
};
console.log(repeatSum(num));

Output

And the output in the console will be −

2
raja
Published on 25-Nov-2020 12:03:49
Advertisements