Find Sum of Digits in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

Digit sum means adding every digit of a number: 123451+2+3+4+5 = 15. Extract digits with % 10 and Math.floor(n / 10), use Math.abs() for negatives, and stop when the value becomes 0. This tutorial covers a live preview, worked JavaScript examples, edge cases, and complexity.

% 10

Last digit

Remainder is the current digit.

Math.floor(n/10)

Drop digit

Floor-divide to peel the next one.

Math.abs(n)

Negatives

Sign usually does not count.

0 → 0

Edge case

Digit sum of zero is zero.

Live Preview

Try 12345

See digits and the sum.

Div by 3 / 9

Bonus fact

Digit sum tests divisibility.

Introduction

Sum of digits is the classic number-manipulation warm-up: peel digits from right to left with % 10 and Math.floor(n / 10), adding each one to a running total. For 12345 you add 5, then 4, then 3, then 2, then 1 — total 15.

Interviews expect Math.abs() for negatives and a clear loop that stops when the remaining value is 0. The same helpers power Armstrong checks, strong numbers, and digital-root / condense problems.

Why it matters?

It teaches base-10 digit extraction — the building block for almost every digit-based interview problem.

Key Highlights

% and //

Extract and drop digits.

Accumulator

total starts at 0.

Math.abs() First

Ignore the sign.

O(digits)

One step per digit.

In short: total += n % 10, then n = Math.floor(n / 10), until n is 0.

📝 Problem & Approach

Given an integer n, return the sum of its decimal digits (sign ignored).

JavaScript
# 12345 -> 1+2+3+4+5 = 15
# -802  -> 8+0+2     = 10
# 0     -> 0

Inputs & Outputs

ItemTypeDescription
nintAny integer (negatives OK).
ReturnintSum of decimal digits.
totalintRunning digit accumulator.

Minimal workflow

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

Method comparison

MethodIdeaNotes
Modulo loop% 10 and Math.floor(n / 10)Interview default
String digitsString(Math.abs(n)).split("").reduce(...)Short, less “numeric”
Condense / digital rootRepeat until one digitNext tutorial step

⚡ Quick Reference

GoalPattern
Ignore signn = Math.abs(n)
Last digitdigit = n % 10
Addtotal += digit
Drop digitn = Math.floor(n / 10)
Stopwhile (n !== 0) (or n > 0)
String style[...String(Math.abs(n))].reduce((a, c) => a + Number(c), 0)

📋 Loop vs String vs Condense

Same digits — different packaging.

Modulo loop
n % 10

Clearest interview answer

String
String(n)

Short JavaScript string style

Trace
print each

Shows peel order

vs condense
repeat

Until one digit left

Context

When This Problem Shows Up

Reach for digit sum whenever you need base-10 peeling.

  1. Interview warm-ups

    First number-manipulation drill.

  2. Armstrong / strong

    Same digit loop, different ops.

  3. Divisibility by 3 or 9

    Digit sum mirrors the test.

  4. Digital root / condense

    Repeat until one digit remains.

  5. Not for floats

    This tutorial focuses on integers.

Key benefit: one tiny loop — % 10 / Math.floor(n / 10) — that unlocks a whole family of digit problems.

🔮 Live Preview

Enter any integer (e.g. 12345 or -802) and see the digits plus their sum.

Any integer in JavaScript safe integer range. Sign is ignored for the sum.

Live result
Press “Compute”.

Examples Gallery

Three complete JavaScript programs — sum digits of 12345, read user input, and trace peeling for a negative value. Click View Output to reveal sample console results.

📚 Getting Started

abs, then peel digits with modulo and floor division.

Example 1 — Sum of Digits (Fixed Number)

Classic example: 12345 → 15.

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)}`);

How It Works

Digits are taken from the right: 5, 4, 3, 2, 1. The accumulator climbs to 15, then the loop stops when the remaining value is 0.

⚡ Reading Input

Same helper, value comes from the user.

Example 2 — Sum of Digits (User Input)

Reads one integer and prints the digit sum. Negatives work because of Math.abs().

JavaScript
function digitSum(number) {
  number = Math.abs(number);
  let total = 0;
  while (number !== 0) {
    total += number % 10;
    number = Math.floor(number / 10);
  }
  return total;
}

// Simulated input (edit this value)
const number = 12345;
console.log(`Sum of digits: ${digitSum(number)}`);

How It Works

Input and summing stay separate: parse once, then reuse digitSum. Try -802 to confirm the sign is ignored.

Example 3 — Trace Digit Peeling for -802

Print each extracted digit so you can see the right-to-left order and the abs step.

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}`);

How It Works

Zero digits still get extracted and add nothing. The sign disappears before the loop, so negatives and positives share the same path.

🧠 How the Algorithm Adds Digits

1

n = Math.abs(n)

Drop the sign before peeling.

Guard
2

digit = n % 10

Take the last digit.

Extract
3

total += digit; n = Math.floor(n / 10)

Accumulate and peel.

Loop
=

Return total

When n becomes 0, you are done.

🔎 Worked Walkthrough — 12345

Watch digits peel from the right while the accumulator climbs to 15.

n beforen % 10total aftern after Math.floor(n / 10)
12345551234
123449123
12331212
122141
11150

Same steps for -802 after abs: 2, then 0, then 8 → total 10.

Use Cases

Where digit sums show up beyond the interview prompt.

1. Interview Basics

Modulo digit extraction drill.

Example: digitSum(12345).

2. Divisibility Tests

Rules for 3 and 9.

Example: Did you know fact.

3. Armstrong / Strong

Same peel, different math.

Example: related links.

4. Checksums

Lightweight digit totals.

Example: validation helpers.

5. Digital Root

Repeat until one digit.

Example: condense tutorial.

6. Next: Condense

Continue the interview chain.

Example: related CTA.

Pro Tip: open with “% 10 takes the digit, Math.floor(n / 10) drops it” before coding.

Advantages

Why the modulo loop is the right first approach.

  1. 1. Pure Numeric

    No string conversion required.

  2. 2. Easy to Trace

    Dry-run 12345 on paper in seconds.

  3. 3. Tiny Memory

    O(1) extra space beyond the input.

  4. 4. Reusable Helper

    Powers Armstrong, strong, condense, and more.

Pro Tip: mention the string one-liner only after you show the numeric loop.

Usage Tips

Small habits that keep digit-sum solutions interview-ready.

  1. 1. Call abs First

    Avoid signed modulo surprises.

  2. 2. Start total at 0

    Same accumulator idea as array sum.

  3. 3. Handle 0 Explicitly

    Or note the loop never runs and returns 0.

  4. 4. Trace Right to Left

    Digits come off the end first.

  5. 5. Link to Condense

    Know the difference: one pass vs repeat.

Pro Tip: sanity-check 0, 12345, and -802 — if those three work, you are solid.

Common Pitfalls

Mistakes that commonly break digit-sum programs.

  1. 1. Forgetting Math.abs()

    Negative remainders confuse beginners.

    → Call Math.abs(n) first.

  2. 2. Using / Instead of //

    Floats break the peel loop.

    → Always floor-divide with //.

  3. 3. Infinite Loop

    Forgetting to update n.

    → Always n = Math.floor(n / 10) inside the loop.

  4. 4. Confusing with Condense

    Stopping at one digit vs one pass.

    → Digit sum is a single pass.

  5. 5. Special-Casing Zero Badly

    Returning wrong values for n = 0.

    → Digit sum of 0 is 0.

Edge Cases

Handle these before claiming the digit sum is complete.

n = 0

Return 0

Sum of digits of 0 is 0.

Negative

Use Math.abs()

Most tasks ignore the sign.

Single digit

Sum = n

7 → 7.

Contains 0

Still peel

0 adds nothing but must be extracted.

Large values

Digit-linear work

Each loop handles one digit.

12345

Classic yes

1+2+3+4+5 = 15.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Divisibility by 3 or 9. A number is divisible by 3/9 iff its digit sum is.
  • Right-to-left peel. % 10 always yields the least significant digit.
  • Digital root. Repeating digit sum until one digit is the next step.
  • d = floor(log10 n) + 1. Time grows with digit count, not with magnitude alone.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Sum 12345

  • Reproduce Example 1
  • Expect 15

2. Trace -802

  • Use abs first
  • Expect 10

3. Handle 0

  • Confirm sum = 0
  • No infinite loop

4. Toward condense

  • Repeat digitSum
  • Until one digit left

Notes

  • Pattern: use modulo and floor division to process digits.
  • Negatives: handle via Math.abs().
  • Complexity: linear in the number of digits.
  • Next skill: repeatedly sum digits until a single digit remains (condense / digital root).

Quick Takeaway: total += n % 10; n = Math.floor(n / 10); repeat until done.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Digit loopO(d)O(1)
String conversionO(d)O(d) for the string
Condense (repeat)O(d) overallO(1)

d is the number of digits — about floor(log10 |n|) + 1 for n ≠ 0.

Wrap Up

🎉 Conclusion

Digit sum peels a number with % 10 and Math.floor(n / 10), adding each digit to a running total. Use Math.abs() for negatives, and remember that 0 sums to 0.

Practice the three examples above, then continue to condensing a number.

total += n % 10; n = Math.floor(n / 10).

💡 Best Practices

✅ Do

  • Call Math.abs(n) first
  • Use % 10 and Math.floor(n / 10)
  • Start total at 0
  • Dry-run 12345
  • Treat 0 as sum 0

❌ Don’t

  • Use / instead of //
  • Forget to update n
  • Ignore the sign
  • Confuse with condense
  • Skip tracing zeros in the middle

Key Takeaways

Knowledge Unlocked

Five things to remember about digit sums

Master the peel loop that powers later digit problems.

5
Core concepts
/ 02

Drop

n = Math.floor(n / 10)

Loop
| 03

abs

ignore sign

Guard
0 04

Zero

sum is 0

Edge
O 05

Cost

O(d)

Analysis

❓ Frequently Asked Questions

Take last digit with n % 10, add it to total, and remove last digit with n = Math.floor(n / 10) until n becomes 0.
In base 10, dividing by 10 leaves a remainder from 0 to 9, which is the last digit.
Use Math.abs(n) so the sign does not affect digit sum.
1 + 2 + 3 + 4 + 5 = 15.
O(d), where d is number of digits.
The digit sum of 0 is 0. Handle it as a special case or let the loop skip.
Digit sum is one pass. Condense repeats digit summing until a single digit remains.
Say % 10 and Math.floor(n / 10) out loud, then dry-run 12345.
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.

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).

Continue to Condense a Number

Learn how to repeatedly sum digits until a single digit remains.

Condense a number 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.

9 people found this page helpful