- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Destructively Sum all the digits of a number in JavaScript
We are required to write a JavaScript function that takes in a number as the only argument. The function should sum the digits of the number while the sum converses to a single digit number.
For example −
If the number is −
const num = 54564567;
Then the function should sum it like this −
5+4+5+6+4+5+6+7 = 42 4+2 = 6
Therefore, the final output should be 6
Example
const num = 54564567; const sumDigits = (num, sum = 0) => { if(num){ return sumDigits(Math.floor(num / 10), sum + (num % 10)); }; return sum; } const sumDestructively = (num) => { let sum = num; while(sum > 9){ sum = sumDigits(sum); }; return sum; } console.log(sumDestructively(num));
Output
And the output in the console will be −
6
- Related Articles
- Recursive sum all the digits of a number JavaScript
- Prime digits sum of a number in JavaScript
- Summing up all the digits of a number until the sum is one digit in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Product sum difference of digits of a number in JavaScript
- Recursive product of all digits of a number - JavaScript
- Sorting digits of all the number of array - JavaScript
- Program to find the sum of all digits of given number in Python
- Difference between product and sum of digits of a number in JavaScript
- Checking whether the sum of digits of a number forms a Palindrome Number or not in JavaScript
- Sum a negative number (negative and positive digits) - JavaScript
- Sum of individual even and odd digits in a string number using JavaScript
- Reduce sum of digits recursively down to a one-digit number JavaScript
- Find the Largest number with given number of digits and sum of digits in C++
- Return an array populated with the place values of all the digits of a number in JavaScript

Advertisements