JavaScript Program to Find Sum of Digits Using Recursion
function sumDigits(n) { if (n === 0) return 0; return n % 10 + sumDigits(Math.floor(n / 10)); } which adds the last digit to the sum of the remaining digits recursively.Examples
How to Think About It
n % 10 to get the last digit and Math.floor(n / 10) to remove it. Keep adding the last digit to the sum of the remaining digits until the number becomes zero.Algorithm
Code
function sumDigits(n) { if (n === 0) return 0; return n % 10 + sumDigits(Math.floor(n / 10)); } console.log(sumDigits(123));
Dry Run
Let's trace sumDigits(123) through the code
Initial call
n = 123, last digit = 3, call sumDigits(12)
Second call
n = 12, last digit = 2, call sumDigits(1)
Third call
n = 1, last digit = 1, call sumDigits(0)
Base case
n = 0, return 0
Return from third call
1 + 0 = 1
Return from second call
2 + 1 = 3
Return from initial call
3 + 3 = 6
| Call | n | Last Digit | Recursive Call | Return Value |
|---|---|---|---|---|
| sumDigits(123) | 123 | 3 | sumDigits(12) | 6 |
| sumDigits(12) | 12 | 2 | sumDigits(1) | 3 |
| sumDigits(1) | 1 | 1 | sumDigits(0) | 1 |
| sumDigits(0) | 0 | - | - | 0 |
Why This Works
Step 1: Base case stops recursion
When n becomes zero, the function returns 0 to stop further recursive calls.
Step 2: Extract last digit
Using n % 10 gets the last digit of the number to add to the sum.
Step 3: Recursive call reduces problem size
Calling the function with Math.floor(n / 10) removes the last digit, making the problem smaller each time.
Alternative Approaches
function sumDigitsStr(n) { if (n.length === 0) return 0; return Number(n[0]) + sumDigitsStr(n.slice(1)); } console.log(sumDigitsStr('123'));
function sumDigitsIter(n) { let sum = 0; while (n > 0) { sum += n % 10; n = Math.floor(n / 10); } return sum; } console.log(sumDigitsIter(123));
Complexity: O(d) time, O(d) space
Time Complexity
The function calls itself once per digit, so time grows linearly with the number of digits d.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to the number of digits.
Which Approach is Fastest?
The iterative approach is faster and uses less memory, but recursion is simpler and clearer for learning.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(d) | O(d) | Learning recursion and clarity |
| String conversion recursion | O(d) | O(d) | When working with digit strings |
| Iteration | O(d) | O(1) | Performance and large inputs |
Math.floor when dividing by 10 causes infinite recursion with decimal numbers.