JavaScript Sum of Digits Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Is the Sum of Digits?

The sum of digits is the total of every digit in a number after one pass. Peel digits with n % 10 and remove them with n = Math.floor(n / 10).

Remember
digitSum(n) = sum of each digit of |n|

Example: 12345
  5 + 4 + 3 + 2 + 1 = 15

One pass only — do not keep summing until one digit
(that is digital root / condense)
nDigitsSum
123451+2+3+4+515
-8028+0+210
000
777

How to Find the Sum of Digits in JavaScript

Four clear steps — modulo and floor division do all the work.

  1. Take Math.abs(n) so negatives share the same path.
  2. While n !== 0, add n % 10 to a total.
  3. Remove the last digit with n = Math.floor(n / 10).
  4. When n becomes 0, return the total.
MethodIdeaTimeBest for
Modulo loop% 10 then Math.floor(/ 10)O(digits)Interviews, default answer
String digitsConvert to string and sum charsO(digits)Quick hacks (less preferred)
Repeated sumKeep summing until one digitO(digits)Digital root / condense

Pseudocode

Pseudocode
function DigitSum(n):
    n = abs(n)
    total = 0

    while n != 0:
        total = total + (n mod 10)
        n = floor(n / 10)

    return total

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Last digitn % 10
Drop digitn = Math.floor(n / 10)
Stop whenn === 0
NegativesMath.abs(n) first
ZeroDigit sum is 0
vs CondenseOne pass only (not digital root)
Classic check12345 → 15

Live Preview

Enter any integer to see each peeled digit and the final digit sum.

Whole numbers only. Absolute value is used for negatives.

Result
n = 12345
Digits (right → left): 5, 4, 3, 2, 1
Sum = 15

JavaScript Programs

Start with a fixed number and the classic modulo loop. Then parse input from a string, and finish by tracing every peeled digit. Each example has a Try it Yourself editor.

Example 1 — Sum of Digits (Fixed Number)

Use % 10 and Math.floor until the number becomes zero.

JavaScript
function digitSum(number) {
  number = Math.abs(number);
  let total = 0;

  while (number !== 0) {
    total += number % 10;
    number = Math.floor(number / 10);
  }

  return total;
}

const number = 12345;
console.log("The sum of digits of " + number + " is: " + digitSum(number));
Try It Yourself

How It Works

  1. Math.abs keeps the helper safe for negatives.
  2. Each loop takes the last digit with number % 10.
  3. Math.floor(number / 10) drops that digit for the next pass.
  4. For 12345 the digits added are 5, 4, 3, 2, then 1.
  5. When number hits 0, return 15.

Example 2 — Sum of Digits (Parsed Input)

Parse one integer from a string and reuse the same helper.

JavaScript
function parseInteger(text) {
  const t = String(text || "").trim();
  if (!/^-?\d+$/.test(t)) {
    return null;
  }
  const n = Number(t);
  if (!Number.isSafeInteger(n)) {
    return null;
  }
  return n;
}

function digitSum(number) {
  number = Math.abs(number);
  let total = 0;

  while (number !== 0) {
    total += number % 10;
    number = Math.floor(number / 10);
  }

  return total;
}

const rawInput = "12345";
const number = parseInteger(rawInput);
if (number === null) {
  console.log("Invalid input");
} else {
  console.log("Input: " + number);
  console.log("Sum of digits: " + digitSum(number));
}
Try It Yourself

How It Works

  1. parseInteger accepts optional leading - and whole digits only.
  2. Invalid or unsafe values return null so callers can reject them.
  3. Pass a valid number to digitSum — parsing and logic stay separate.
  4. Try -802 in the editor to confirm the answer is 10.
  5. Same algorithm as Example 1 with a different data source.

Example 3 — Trace Digit Peeling for -802

Print each extracted digit so the right-to-left order is obvious.

JavaScript
const n = -802;
let x = Math.abs(n);
let total = 0;

console.log("Starting from Math.abs(" + n + ") = " + x);
while (x !== 0) {
  const digit = x % 10;
  total += digit;
  console.log("  take " + digit + ", remaining " + Math.floor(x / 10)
    + ", total=" + total);
  x = Math.floor(x / 10);
}

console.log("Digit sum: " + total);
Try It Yourself

How It Works

  1. Absolute value turns -802 into 802 before peeling.
  2. Digits arrive as 2, then 0, then 8.
  3. A zero digit still counts as a step but adds nothing.
  4. When remaining is 0, the loop stops.
  5. Final digit sum is 10.

Edge Cases & Pitfalls

Check these before calling the solution done.

Zero

Digit sum is 0

The loop body never runs when n is already 0, so the total stays 0.

Negatives

Use Math.abs

JavaScript % keeps the dividend’s sign. Normalize first for a clean digit sum.

Floor

Always floor-divide

Plain n / 10 leaves a float. Use Math.floor so digits peel correctly.

One pass

Do not over-sum

Digit sum stops after one pass. Repeating until one digit is digital root / condense.

Time and Space Complexity

ProgramTimeExtra space
Modulo digit loopO(digits) = O(log n)O(1)
Parsed input + digit sumO(digits)O(1)
Trace peelO(digits)O(1)

Each digit is visited once. The number of digits grows like log₁₀ n.

Key Takeaways

  • Core tools: n % 10 peels a digit; Math.floor(n / 10) drops it.
  • One pass: stop when n becomes 0 — that is digit sum, not digital root.
  • Signs: use Math.abs before peeling.
  • Test set: 12345 → 15; −802 → 10; 0 → 0; 7 → 7.

One line: keep adding n % 10 and floor-dividing by 10 until nothing is left.

Frequently Asked Questions

Take the last digit with n % 10, add it to a total, then remove it with n = Math.floor(n / 10). Repeat until n becomes 0.
In base 10, the remainder when dividing by 10 is always the rightmost digit (0 through 9).
JavaScript division always returns a float. Math.floor(n / 10) drops the last digit the same way integer /= 10 does in Java or C.
Use Math.abs(n) first so the sign does not affect the digit sum.
Digit sum is one pass. Condensing (digital root) repeats digit summing until only one digit remains.
O(d), where d is the number of digits — equivalently O(log n) for positive n.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Next: Swap Two Numbers

Exchange two values with a temp variable or arithmetic tricks.

Swap two numbers tutorial →

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.

15 people found this page helpful