Find Sum of Digits in JavaScript
What you’ll learn
- How to extract digits using
% 10and/ 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.
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
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 sumSum of digits (fixed number)
Matches the classic demo: 12345 gives 15.
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);Sum of digits (user input)
Reads a number from the user and prints the sum of its digits.
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);
}❓ FAQ
🔄 Input / output examples
| Input | Digit sum | Explanation |
|---|---|---|
12345 | 15 | 1+2+3+4+5 |
-802 | -6 | Signed first digit: -8+0+2 |
0 | 0 | Special case |
Edge cases and pitfalls
These are the common mistakes in digit problems.
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.
Decide how to handle sign
This page uses signed first digit for negatives (for example -802 -> -8 + 0 + 2).
Input parsing rule
Allow only optional leading - followed by digits. Reject mixed text so the computed sum is predictable.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Loop through digits | O(d) | O(1) |
Summary
- Core loop:
sum += n % 10, thenn /= 10. - Negatives: apply sign to the first digit (example:
-802 => -6). - Complexity: linear in number of digits.
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).
9 people found this page helpful
