Recursively adding digits of a number in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We are required to write a JavaScript function that takes in a number and recursively adds the digits of the number until the result is not a single digit number.

For example, If the number is −

54563

Then the output should be 5, because,

= 5 + 4 + 5 + 6 + 3
= 23
= 2 + 3
= 5

Example

The code for this will be −

const num = 54563;
const addRecursively = num => {
   if(num < 10){
      return num;
   };
   let sum = 0;
   while(num !== 0) {
      sum += (num%10);
      num = parseInt(num/10);
   };
   return addRecursively(sum);
};
console.log(addRecursively(num));

Output

The output in the console −

3
raja
Published on 10-Oct-2020 07:55:42
Advertisements