Emmanuel Akinfulubi

JavaScriptMath

Digital root of a number in JavaScript

Beginner · 4 min read

Take a number, add up its digits, and if the answer has more than one digit, add up those digits too. Keep going until one digit is left. That last digit is the digital root. For 9875 the digits add up to 29, then 2 + 9 is 11, then 1 + 1 is 2. So the digital root of 9875 is 2.

Digit sums are used in check digits on account and card numbers, and the digital root is behind an old trick for checking sums by hand called "casting out nines". In this tutorial you will write a digit sum two ways, one with strings and one with arithmetic, then the digital root two ways. You will also find a number where the string version quietly returns NaN. You need to know loops, % and arrow functions.

Peeling off digits with % and Math.floor

You can get the last digit of a whole number with % 10, the remainder after dividing by 10. You can drop the last digit with Math.floor(n / 10), which divides and throws away the decimal part.

JavaScript

console.log(9875 % 10);             // 5
console.log(Math.floor(9875 / 10)); // 987

Repeat those two moves and you visit every digit, from right to left, until nothing is left.

Why NaN matters here

NaN means "not a number". You get it from Number('e'), for example. Any sum that includes NaN also becomes NaN, with no error to warn you. Keep that in mind for Step 5.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

42 Digit sum and digital root

easy

Add up a number's digits, then keep adding until one digit is left. Do it twice: once by string, once by arithmetic, and find the input where the string version gives NaN.

Stuck? Three hints, smallest first
  1. 1. The arithmetic version peels digits off with n % 10 and Math.floor(n / 10).
  2. 2. The digital root has a closed form for positive n: 1 + (n - 1) % 9.
  3. 3. String(1e21) is not 22 characters of digits.

Step 1: a digit sum with a loop

Step 1

function digitSum(n) {
  n = Math.abs(n);
  let sum = 0;
  while (n > 0) {
    sum += n % 10;
    n = Math.floor(n / 10);
  }
  return sum;
}
console.log(digitSum(9875)); // 29
console.log(digitSum(-45));  // 9
console.log(digitSum(0));    // 0

Math.abs drops a minus sign first, so -45 is treated as 45. For 0 the loop never runs and the sum stays 0, which is the right answer.

Step 2: a digit sum with a string

The other common approach turns the number into text, splits it into characters, and adds them up.

Step 2

const digitSumByString = (n) =>
  String(Math.abs(n)).split('').reduce((sum, ch) => sum + Number(ch), 0);
console.log(digitSumByString(9875)); // 29

split('') gives ['9', '8', '7', '5'], and Number(ch) turns each character back into a number before reduce adds it. Same answer, and many people find it easier to read.

Step 3: fold until one digit is left

The digital root is just the digit sum, repeated while the number is bigger than 9.

Step 3

const digitalRootByLoop = (n) => {
  n = Math.abs(n);
  while (n > 9) n = digitSum(n);
  return n;
};
console.log(digitalRootByLoop(9875)); // 2
console.log([9875, digitSum(9875), digitSum(29), digitSum(11)]); // [ 9875, 29, 11, 2 ]

The second line shows the chain one fold at a time: 9875, then 29, then 11, then 2.

Step 4: the shortcut with no loop

Adding up digits never changes a number's remainder when you divide by 9. So the digital root is the remainder after dividing by 9, except that a remainder of 0 shows up as 9 (for 18, the digits add to 9, not 0). The formula 1 + (n - 1) % 9 does exactly that for positive n:

Step 4

const digitalRoot = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));
console.log(digitalRoot(9875)); // 2
console.log([9, 18, 99, 123456789].map(digitalRoot)); // [ 9, 9, 9, 9 ]

Zero needs its own branch: its root is 0, and the formula is written for positive numbers.

You can check the shortcut against the loop on many numbers at once:

JavaScript

const agree = Array.from({ length: 200 }, (_, i) => i)
  .every((n) => digitalRoot(n) === digitalRootByLoop(n));
console.log(agree); // true

Step 5: the number that breaks the string version

Now try a very large number, 1e21, which is 1 followed by 21 zeros.

Step 5

console.log(String(1e21));           // 1e+21
console.log(digitSumByString(1e21)); // NaN
console.log(digitSum(1e21));         // 1

From 1e21 upward, String writes numbers in exponential notation. The string version then meets the characters e and +, Number('e') is NaN, and NaN spreads through the rest of the sum. No error is thrown. The arithmetic version never looks at text, so it still gets 1.

If you really need every digit of a huge whole number, BigInt(n).toString() always writes out all of them.

The full solution

The answer panel has both digit sums, the looping digital root and the closed form, then prints the chain for 9875 and the 1e21 case side by side. Press Run to see the output.

The answer

const digitSumByString = (n) =>
  String(Math.abs(n)).split('').reduce((sum, ch) => sum + Number(ch), 0);

function digitSum(n) {
  n = Math.abs(n);
  let sum = 0;
  while (n > 0) {
    sum += n % 10;
    n = Math.floor(n / 10);
  }
  return sum;
}

const digitalRootByLoop = (n) => {
  n = Math.abs(n);
  while (n > 9) n = digitSum(n);
  return n;
};

// Same answer, no loop: the root is n mod 9, with 9 in place of 0.
const digitalRoot = (n) => (n === 0 ? 0 : 1 + ((Math.abs(n) - 1) % 9));

const chain = [9875, digitSum(9875), digitSum(29), digitSum(11)];

console.log('digit sum of 9875 :', digitSum(9875));
console.log('the chain to a root:', chain);
console.log('closed form        :', digitalRoot(9875));
console.log('String(1e21)       :', String(1e21));
console.log('by string          :', digitSumByString(1e21), '<- the e and the + are not digits');
console.log('by arithmetic      :', digitSum(1e21));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the digits of 9875 sum to 29', [digitSum(9875), digitSumByString(9875)], [29, 29]);
test('and folding again gives 11, then 2', chain, [9875, 29, 11, 2]);
test('so the digital root is 2', digitalRootByLoop(9875), 2);
test('the closed form agrees for every n up to 200', Array.from({ length: 200 }, (_, i) => i).every((n) => digitalRoot(n) === digitalRootByLoop(n)), true);
test('zero sums to zero, and the sign is ignored', [digitSum(0), digitSum(-45)], [0, 9]);
test('multiples of 9 have a root of 9, not 0', [9, 18, 99, 123456789].map(digitalRoot), [9, 9, 9, 9]);
test('String(1e21) is exponential notation', String(1e21), '1e+21');
test('so the string version returns NaN there', Number.isNaN(digitSumByString(1e21)), true);
test('while the arithmetic version still gets 1', digitSum(1e21), 1);

The digital root is congruence in disguise: adding digits does not change a number's remainder modulo 9, so folding repeatedly lands on that remainder, with 9 standing in for 0. Hence 1 + (n - 1) % 9, and hence the old trick of casting out nines to check a sum by hand.

The NaN is the trap. String(n) switches to exponential form at 1e21, so a digit walker built on strings meets 'e' and '+', Number('e') is NaN, and NaN propagates through the rest of the fold without an error. The arithmetic version has no such cliff, and if you genuinely need digits of enormous integers, BigInt(n).toString() never abbreviates.

Common mistakes

  • Stopping after one digit sum. The digit sum of 9875 is 29, but the digital root keeps going to 2.
  • Using n % 9 on its own. Multiples of 9 have a root of 9, not 0. Use 1 + (n - 1) % 9 and handle 0 separately.
  • Trusting String(n) for big numbers. Past 1e21 it gives '1e+21', and a string digit walker returns NaN without complaint.

Try it yourself

  1. Change digitSumByString to skip any character that isn't a digit. What does it return for 1e21 now, and is that the right answer?
  2. Write isDivisibleBy9(n) using digitalRoot.
  3. Count how many steps digitalRootByLoop takes for 999999999999. (Hint: add a counter inside the loop.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.