JavaScript Program to Find Sum of Digits
split(''), map(Number), and reduce((a, b) => a + b, 0) like this: const sum = num => num.toString().split('').map(Number).reduce((a, b) => a + b, 0);Examples
How to Think About It
Algorithm
Code
function sumOfDigits(num) { return num.toString().split('').map(Number).reduce((a, b) => a + b, 0); } console.log(sumOfDigits(123)); // Output: 6
Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Convert number to string
123 becomes '123'
Split string into digits
'123' becomes ['1', '2', '3']
Convert each digit to number
['1', '2', '3'] becomes [1, 2, 3]
Sum all digits
1 + 2 + 3 = 6
| Step | Digits Array | Sum So Far |
|---|---|---|
| Start | ['1', '2', '3'] | 0 |
| Add 1 | [1, 2, 3] | 1 |
| Add 2 | [1, 2, 3] | 3 |
| Add 3 | [1, 2, 3] | 6 |
Why This Works
Step 1: Convert number to string
Using toString() lets us treat the number like text so we can look at each digit separately.
Step 2: Split string into characters
The split('') method breaks the string into an array of single characters, each representing a digit.
Step 3: Convert characters to numbers
Using map(Number) changes each character back into a number so we can add them.
Step 4: Sum the digits
The reduce method adds all the numbers in the array to get the total sum.
Alternative Approaches
function sumOfDigits(num) { let sum = 0; while (num > 0) { sum += num % 10; num = Math.floor(num / 10); } return sum; } console.log(sumOfDigits(123)); // Output: 6
function sumOfDigits(num) { if (num === 0) return 0; return (num % 10) + sumOfDigits(Math.floor(num / 10)); } console.log(sumOfDigits(123)); // Output: 6
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each digit once, so the time grows linearly with the number of digits, making it O(n).
Space Complexity
Converting the number to a string and then to an array uses extra space proportional to the number of digits, so O(n).
Which Approach is Fastest?
The loop with modulo method uses constant space O(1) and is generally faster for large numbers compared to string conversion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String conversion with map and reduce | O(n) | O(n) | Simplicity and readability |
| Loop with modulo operator | O(n) | O(1) | Performance with large numbers |
| Recursion | O(n) | O(n) | Elegant code but less efficient for big inputs |