
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursively Adding Digits of a Number in JavaScript
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
Advertisements