Find Sum of Digits in JavaScript

Beginner
⏱️ 7 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit math

What you’ll learn

  • How to extract digits using % 10 and / 10.
  • The accumulator pattern: sum += digit.
  • A clean JavaScript solution with a simple loop and safe handling of negative input.

Overview

To find the sum of digits of a number, you repeatedly take the last digit, add it, and remove it. For example, 12345 becomes 5 (add), then 1234, then 4 (add), and so on.

Two programs

Example 1 uses a fixed number = 12345. Example 2 reads the number from the user.

Live preview

Type a number and see the digits added up as an expression (like 1 + 2 + 3).

Next step

If you repeat digit sums until one digit remains, you get the digital root (see “Condense a number”).

Live preview

Enter an integer (example: 12345 or -802) and see the sum of digits.

Uses base-10 digits. For negatives, the sign is applied to the first digit (example: -802 => -8 + 0 + 2).

Live result
Press “Compute”.

Algorithm

Goal: compute the sum of digits of an integer n.

Read sign + digits

If input starts with -, apply that sign to the first digit only.

Extract and add digits

Walk through all digits and add them. For a negative input, first digit contributes a negative value.

Handle n = 0

If the input is 0, the sum of digits is 0.

📜 Pseudocode

Pseudocode
function digitSum(text):
    if text is not a signed integer: invalid
    sign ← -1 if text starts with '-', else +1
    digits ← all numeric characters in text
    if digits = "0": return 0
    sum ← 0
    for each digit with index i in digits:
        value ← numeric(digit)
        if i = 0 and sign = -1: value ← -value
        sum ← sum + value
    return sum
1

Sum of digits (fixed number)

Matches the classic demo: 12345 gives 15.

JavaScript
function digitSum(rawInput) {
  const text = String(rawInput).trim();
  const negative = text.startsWith("-");
  const digits = text.replace(/^-/, "").split("");
  if (digits.length === 1 && digits[0] === "0") return 0;

  let sum = 0;
  for (let i = 0; i < digits.length; i++) {
    let value = Number(digits[i]);
    if (i === 0 && negative) value = -value;
    sum += value;
  }
  return sum;
}

const input = "12345";
const result = digitSum(input);
console.log("The sum of digits of " + input + " is: " + result);
Try it Yourself
2

Sum of digits (user input)

Reads a number from the user and prints the sum of its digits.

JavaScript
function digitSum(rawInput) {
  const text = String(rawInput).trim();
  if (!/^-?\d+$/.test(text)) return null;

  const negative = text.startsWith("-");
  const digits = text.replace(/^-/, "").split("");
  if (digits.length === 1 && digits[0] === "0") return 0;

  let sum = 0;
  for (let i = 0; i < digits.length; i++) {
    let value = Number(digits[i]);
    if (i === 0 && negative) value = -value;
    sum += value;
  }
  return sum;
}

const rawInput = "-802";
const sum = digitSum(rawInput);
if (sum === null) {
  console.log("Invalid input.");
} else {
  console.log("Sum of digits: " + sum);
}
Try it Yourself

❓ FAQ

Repeat: take the last digit with n % 10, add it to sum, then remove the last digit with n /= 10. Stop when n becomes 0.
In base 10, dividing by 10 leaves a remainder from 0 to 9. That remainder is exactly the last digit.
On this page, we keep the sign on the first digit. Example: -802 is treated as -8 + 0 + 2, so the sum is -6.
1 + 2 + 3 + 4 + 5 = 15.
O(d) where d is the number of digits, because you process one digit per loop iteration.

🔄 Input / output examples

InputDigit sumExplanation
12345151+2+3+4+5
-802-6Signed first digit: -8+0+2
00Special case

Edge cases and pitfalls

These are the common mistakes in digit problems.

n = 0

Loop runs zero times

If you use while (n != 0), then for n = 0 the loop doesn’t run. That is fine, but make sure you return 0 as the digit sum.

Negative

Decide how to handle sign

This page uses signed first digit for negatives (for example -802 -> -8 + 0 + 2).

INT_MIN

Input parsing rule

Allow only optional leading - followed by digits. Reject mixed text so the computed sum is predictable.

⏱️ Time and space complexity

ApproachTimeExtra space
Loop through digitsO(d)O(1)

Summary

  • Core loop: sum += n % 10, then n /= 10.
  • Negatives: apply sign to the first digit (example: -802 => -6).
  • Complexity: linear in number of digits.
Did you know?

Digit sum is used in quick checks like divisibility by 3 and 9: a number is divisible by 3 (or 9) exactly when its digit sum is divisible by 3 (or 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.

9 people found this page helpful