JavaScript: Sum of the digits of a number
JavaScript Math: Exercise-68 with Solution
Write a JavaScript program to calculate the sum of a given number's digits.
In mathematics, the digit sum of a natural number in a given number base is the sum of all its digits. For example, the digit sum of the decimal number 6098 would be 6+0+9+8=23.
Sample Data:
6098 -> 23
-501 -> 6
2546 -> 17
Sample Solution-1:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript function to sum of the digits of a number</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function sum_Of_Digits(n) {
if (n < 0) n = -n
let result = 0
while (n > 0)
{
result += n % 10
n = Math.floor(n / 10)
}
return result
}
console.log(sum_Of_Digits(6098))
console.log(sum_Of_Digits(-501))
console.log(sum_Of_Digits(2546))
Sample Output:
23 6 17
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-68 by w3resource (@w3resource) on CodePen.
Sample Solution-2:
JavaScript Code:
function sum_Of_Digits(n) {
if (n < 0) n = -n
if (n < 10) return n
return (n % 10) + sum_Of_Digits(Math.floor(n / 10))
}
console.log(sum_Of_Digits(6098))
console.log(sum_Of_Digits(-501))
console.log(sum_Of_Digits(2546))
console.log(sum_Of_Digits(10))
console.log(sum_Of_Digits(5))
Sample Output:
23 6 17 1 5
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-68-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Sum of a geometric progression.
Next: Find all prime numbers below a given number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Randomizes the order of the values of an array, returning a new array
Example:
const tips_shuffle = ([...arr]) => { let x = arr.length; while (x) { const i = Math.floor(Math.random() * x--); [arr[x], arr[i]] = [arr[i], arr[x]]; } return arr; }; const foo = [2, 4, 6]; console.log(tips_shuffle(foo));
Output:
[4, 2, 6]
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook