Numbers · beginner
JavaScript Program to Find the Sum of Digits of a Number
Find the sum of the digits of a number in JavaScript with a while loop using % and Math.trunc(), and in one line with split() and reduce(), negatives included.
- while loop
- remainder %
- Math.trunc()
- Math.abs()
The sum of digits of 4721 is 4 + 7 + 2 + 1 = 14. The arithmetic method shows how to take a number apart: n % 10 is the last digit, and Math.trunc(n / 10) removes it. JavaScript has no integer division operator, so the truncation matters.
The program
function digitSum(n) {
n = Math.abs(n);
let total = 0;
while (n > 0) {
total += n % 10;
n = Math.trunc(n / 10);
}
return total;
}
console.log(digitSum(4721));
console.log(digitSum(-905));
console.log(digitSum(0));14
14
0How it works
- Math.abs(n) drops the minus sign, so -905 is handled like 905.
- n % 10 is the last digit (4721 % 10 is 1), which is added to total.
- Math.trunc(n / 10) divides by 10 and drops the fraction: 4721 becomes 472.
- When n reaches 0 there are no digits left and the loop ends. For 0 the loop never runs.
Watch it run line by line
Inside digitSum watch n shrink (4721, 472, 47, 4, 0) while total grows (1, 3, 10, 14). The while line is a step of its own each time the condition is tested.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: One line with split() and reduce()
Converting to a string and adding up the digits is shorter and fine for everyday code.
const digitSum = (n) => String(Math.abs(n)).split("").reduce((sum, d) => sum + Number(d), 0);
console.log(digitSum(4721));14Common mistakes
- Using n / 10 without Math.trunc(): n becomes 472.1, 47.21, … and the loop runs hundreds of times.
- Forgetting Math.abs(): for a negative number the while (n > 0) loop never runs.
- Using Math.floor() for negative numbers without abs(): Math.floor(-9.05) is -10, not -9.
Try it yourself
- Reverse a number with the same loop: result = result * 10 + n % 10.
- Repeat the sum until one digit is left (the digital root): 4721 → 14 → 5.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.