- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum up a number until it becomes 1 digit JavaScript
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
Advertisements