Sum the digits of a number in JavaScript
Beginner · 4 min read
Adding up the digits of a number, so 1234 gives 1 + 2 + 3 + 4 = 10, is a small exercise that shows up in more places than you might expect. Check digits on bank account and card numbers use digit sums to catch typing mistakes. Puzzles and number games use them. And it is a good way to practise moving between numbers and text.
In this tutorial you will write digitSum(n), then digitalRoot(n), which keeps adding the digits until only one digit is left: 1234 gives 10, and 10 gives 1. You need to know what a function and a while loop are. The rest is explained below.
Numbers and text
A number has no "digits" you can loop over. Its text does. String(n) turns a number into text, and Number(text) turns text back into a number:
console.log(String(1234)); // 1234, now as text
console.log(String(1234).split('')); // [ '1', '2', '3', '4' ]
console.log(Number('3') + 1); // 4
split('') cuts the text between every character, so each digit becomes its own item. Each item is still text, '3' rather than 3, which is why Number is needed before you add.
Why you must convert
Adding text to text joins it instead of adding:
console.log('1' + '2'); // 12, as text: the two pieces were joined
console.log(1 + 2); // 3
Forgetting Number is the most common bug in this exercise.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
29 Sum the digits of a number
easyAdd up the digits of a whole number. Then reduce it repeatedly until a single digit is left.
Stuck? Three hints, smallest first
- 1. Split the text form and add, or use
% 10and integer division in a loop. - 2. For the repeated version, keep going while the value is 10 or more.
- 3. The single-digit result equals
1 + (n - 1) % 9for positive n, which is a neat cross-check.
Step 1: add up the digits
Split the text into digits, then use reduce to add them. reduce carries a running total from item to item, starting at 0:
const digitSum = (n) => String(n).split('').reduce((total, d) => total + Number(d), 0);
console.log(digitSum(1234)); // 10
console.log(digitSum(99)); // 18
console.log(digitSum(0)); // 0
Step 2: negative numbers
Try a negative number with Step 1's version:
const digitSum = (n) => String(n).split('').reduce((total, d) => total + Number(d), 0);
console.log(String(-456).split('')); // [ '-', '4', '5', '6' ]
console.log(digitSum(-456)); // NaN
The minus sign became an item. Number('-') is NaN ("Not a Number"), and anything plus NaN is NaN. The digits of -456 are still 4, 5 and 6, so drop the sign first with Math.abs, which gives the number without its sign:
function digitSum(n) {
return String(Math.abs(n))
.split('')
.reduce((total, d) => total + Number(d), 0);
}
console.log(digitSum(-456)); // 15
console.log(digitSum(1234)); // 10
Step 3: repeat until one digit is left
The digital root keeps going. 9875 has digits summing to 29, 29 gives 11, and 11 gives 2. A while loop is the natural fit, because you don't know in advance how many rounds it will take. Keep summing as long as the value has two or more digits, which means as long as it is 10 or more:
function digitalRoot(n) {
let value = Math.abs(n);
while (value >= 10) value = digitSum(value);
return value;
}
console.log(digitalRoot(1234)); // 1
console.log(digitalRoot(99)); // 9
console.log(digitalRoot(9875)); // 2
For 99: the digits sum to 18, and 18 is still 10 or more, so go round again: 1 + 8 is 9. Done.
Step 4: check it against a formula
There is a shortcut. For any positive whole number, the digital root is 1 + (n - 1) % 9, where % is the remainder after dividing. It works because a number and its digit sum always leave the same remainder when divided by 9. Zero is a special case, with a root of 0.
const rootFormula = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));
console.log(rootFormula(1234)); // 1
console.log(rootFormula(9875)); // 2
A formula like this makes an excellent test. Instead of checking a few numbers you picked by hand, check that the loop and the formula agree on every number from 1 to 50:
const ones = Array.from({ length: 50 }, (_, i) => i + 1);
console.log(ones.every((n) => digitalRoot(n) === rootFormula(n))); // true
Array.from({ length: 50 }, (_, i) => i + 1) builds the list 1 to 50. every returns true only if the test passes for each one. Two completely different methods agreeing fifty times is far stronger evidence than a handful of examples.
The full solution
The complete answer has digitSum, digitalRoot and the formula, prints both results for several numbers including 0 and a negative, and cross-checks the loop against the formula. Press Run to see the output.
function digitSum(n) {
return String(Math.abs(n))
.split('')
.reduce((total, d) => total + Number(d), 0);
}
function digitalRoot(n) {
let value = Math.abs(n);
while (value >= 10) value = digitSum(value);
return value;
}
// The closed-form shortcut, for cross-checking.
const rootFormula = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));
for (const n of [1234, 99, 9875, 0, -456]) {
console.log(n, 'digits sum to', digitSum(n), '-> root', digitalRoot(n));
}
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('1234', digitSum(1234), 10);
test('99', digitSum(99), 18);
test('a negative uses its digits', digitSum(-456), 15);
test('zero', digitSum(0), 0);
test('root of 1234', digitalRoot(1234), 1);
test('root of 99', digitalRoot(99), 9);
test('the formula agrees for 1..50', Array.from({ length: 50 }, (_, i) => i + 1).every((n) => digitalRoot(n) === rootFormula(n)), true);
test('and for zero', rootFormula(0), 0);
The cross-check is the interesting part. The digital root of any positive number is 1 + (n - 1) % 9, which follows from the fact that a number and its digit sum leave the same remainder when divided by 9. Checking the loop against the formula for fifty values is far stronger evidence than a handful of hand-picked cases.
Common mistakes
- Adding the digits as text.
'1' + '2'is'12'. Convert each digit withNumberfirst. - Not dropping the minus sign.
Number('-')isNaN, and oneNaNspoils the whole sum. - Summing only once for the digital root. 99 sums to 18, which still has two digits. Keep going while the value is 10 or more.
Try it yourself
- Rewrite
digitSumwithout strings: usen % 10to get the last digit andMath.floor(n / 10)to drop it, in a loop. - Write
digitCount(n)that returns how many digits a number has. - A number divides evenly by 3 exactly when its digit sum does. Use
digitSumto check this for 123, 124 and 999.