Condense a Number (Digital Root) in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Digit manipulation

What you’ll learn

  • How repeated digit sums produce the digital root (the usual meaning of “condense” here).
  • An iterative script matching the reference flow, plus an O(1) base-10 formula (with BigInt for wide literals that do not fit IEEE doubles exactly).
  • A live preview, modular arithmetic intuition (mod 9), and edge cases such as zero and large magnitudes.

Overview

Starting from a nonnegative integer, sum its decimal digits; if the result still has more than one digit, repeat. The final single digit is the digital root. Example: 9875 → 29 → 11 → 2.

Two programs

Iterative peel (reference style) and a closed form using % 9 (plus BigInt when needed).

Live preview

Type a nonnegative integer and see the condensed digit.

Terminology

Clarifies digital root vs a single digit sum pass.

Prerequisites

Decimal representation, % 10 and integer division for digit peeling, and nested loops.

  • console.log, Number.isSafeInteger, and optional BigInt literals (123n).
  • Why 999999999999999999n matters: the plain Number literal rounds; BigInt keeps all eighteen decimal nines exact.

Digital root vs digit sum

The digit sum of 9875 is 9+8+7+5 = 29. That is not yet one digit. The digital root keeps summing digits until the value lies in 0..9; here 29 → 11 → 2.

Many tutorials call this process “condensing” the number. It is not a different base; it is repeated reduction in base ten.

One pass digit sum
Repeat digital root
mod 9 closed form

Congruence mod 9

Because 10 ≡ 1 (mod 9), every decimal digit expansion satisfies n ≡ s(n) (mod 9) where s(n) is the digit sum. The same congruence holds after each condensation step, so the digital root is determined by n mod 9 with the usual 9 substitution for nonzero multiples of 9.

9875

9875 mod 9 = 2, matching the iterated sum chain ending at 2.

Intuition

18 Root 9
Chain
1+8 = 9
49 Root 4
Chain
13 → 4

Takeaway: each digit-sum step preserves the value modulo 9 (except the bookkeeping that maps a remainder of 0 to digital root 9 for positive n).

Live preview

Nonnegative integers in the JavaScript safe integer range. Uses the same repeated digit-sum rule as Example 1.

Negative values are not supported in this widget (match Example 1’s assumption).

Live result
Press “Condense” to see the digital root.

Algorithm (iterative)

Goal: reduce a nonnegative integer to a single decimal digit by repeated digit summation.

While the working value exceeds 9

Replace it by the sum of its decimal digits (peel with % 10 and integer division by 10).

Stop

Return the last value (already in 0..9).

📜 Pseudocode

Pseudocode
function condense(n):  // n ≥ 0
    while n > 9:
        sum ← 0
        t ← n
        while t > 0:
            sum ← sum + (t mod 10)
            t ← floor(t / 10)
        n ← sum
    return n
1

Iterative condensation (reference flow)

Uses a working copy n so the outer loop condition is clear. Assumes nonnegative number; the outer const number is unchanged while condenseNumber runs.

JavaScript
function condenseNumber(number) {
  let n = number;

  while (n > 9) {
    let sum = 0;
    let tmp = n;

    while (tmp > 0) {
      sum += tmp % 10;
      tmp = Math.floor(tmp / 10);
    }

    n = sum;
  }

  return n;
}

const number = 9875;
const condensedNumber = condenseNumber(number);

console.log("The condensed form of " + number + " is: " + condensedNumber);
Try it Yourself

Explanation

The inner loop destroys tmp on each pass; n holds the next value to condense. The binding number in the caller is unchanged because primitives are passed by value.

while (n > 9)

Stopping rule. Single-digit results (including 0) exit immediately.

2

Closed form (mod 9) with BigInt for wide literals

Same mathematical answer for nonnegative inputs in a single step. 9875 uses Number; eighteen decimal nines use BigInt so the value is not rounded by IEEE-754.

JavaScript
/** @param {number} n  integer, n >= 0, within Number.MAX_SAFE_INTEGER */
function digitalRootNonnegativeNumber(n) {
  if (n === 0) {
    return 0;
  }
  const r = n % 9;
  return r === 0 ? 9 : r;
}

/** @param {bigint} n  n >= 0 */
function digitalRootNonnegativeBigInt(n) {
  if (n === 0n) {
    return 0;
  }
  const r = n % 9n;
  return r === 0n ? 9 : Number(r);
}

const a = 9875;
const b = 999999999999999999n; /* 18 nines — must be BigInt */

console.log("dr(" + a + ") = " + digitalRootNonnegativeNumber(a) + " (closed form)");
console.log("dr(" + b + ") = " + digitalRootNonnegativeBigInt(b) + " (closed form)");
Try it Yourself

Explanation

Eighteen nines sum to 162, whose digit sum is 9; the shortcut returns 9 immediately because n % 9n === 0n for that positive BigInt.

return r === 0n ? 9 : Number(r);

Map remainder 0n to root 9 for positive multiples of nine.

Optimization

mod 9 trick. Use the closed form when n is wide; it avoids repeated scans of long digit strings.

Big integers. If n is stored as a string, either iterate digits once per round or reduce mod 9 in one pass over characters without building a huge Number.

Interview: define nonnegative policy, give 9875 trace, then cite the mod 9 formula.

❓ FAQ

It means the digital root: repeatedly replace the number by the sum of its decimal digits until a single digit remains. Example: 9875 → 9+8+7+5 = 29 → 2+9 = 11 → 1+1 = 2.
No. A single pass digit sum is not always one digit. Condensing (digital root) repeats until the value is in 0..9 (with 0 only for input 0 in the usual convention on this page).
For n > 0: let r = n % 9. The digital root is 9 if r == 0, else r. For n == 0, the digital root is 0. This follows because 10 ≡ 1 (mod 9), so n and its digit sum are congruent mod 9.
The process uses digit sums, but the mathematical name of the final single-digit result is the digital root. Using both terms is fine if you keep the iteration vs one-shot distinction clear.
The iterative code on this page assumes nonnegative integers (like the original). For interviews, define a policy: often digital root uses |n| for n ≠ 0, or reject negatives.
Iterative: each round costs O(d) in the number of digits d; the number of rounds is small for 32-bit ints. The closed form is O(1) time and O(1) space.

🔄 Input / output examples

Change the const literals or read from prompt / process.stdin in Node for interactive tests.

InputDigital rootNotes
98752Reference walkthrough
00Both programs
99Already one digit
1891+8

Edge cases and pitfalls

The reference loop while (n > 9) never terminates for some negative conventions if you feed negatives in—keep inputs nonnegative or normalize first.

Zero

n = 0

The outer while is skipped; digital root 0. The closed form must special-case n == 0 before the 9 substitution.

Multiples of 9

n % 9 == 0, n > 0

The root is 9, not 0. Mixing that up breaks the closed form.

Types

Wide literals

Iterative summation on huge values needs exact integers; BigInt plus % 9n is simpler than trusting Number past MAX_SAFE_INTEGER.

Other bases

Beyond decimal

The mod 9 shortcut is specific to base ten. Other bases use different moduli.

⏱️ Time and space complexity

ApproachTimeExtra space
Iterative (safe Number)Small constant number of digit passesO(1)
Iterative (asymptotic)O(D · R) digit work (digits D, rounds R; both tiny for interview int)O(1)
Closed formO(1) for Number; O(1) modulo cost for BigInt at fixed widthO(1)

For very large n as a string, one digit pass per round is O(L) per round in string length L.

Summary

  • Idea: repeated digit sum until one digit—the digital root.
  • Code: nested loops, or n === 0 ? 0 : (n % 9 === 0 ? 9 : n % 9) for nonnegative Number; mirror with BigInt when needed.
  • Watch-outs: clarify vs one-shot digit sum, 0, multiples of 9, negatives, and Number precision.
Did you know?

In base ten, the digital root (this page’s “condensed” value) is related to divisibility by 9: for n > 0, repeated digit sums eventually match 1 + (n - 1) % 9, with 9 instead of 0 when n is a nonzero multiple of 9.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful