In this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by adding each number from a given integer. There are many ways to find the sum of the digits of a number. We will see some of the approaches –
Table of Contents
Using for loop
You can use a for loop to manually extract each number using modulo (%) and division (/).
function sumOfDigitsForLoop(num) {
let sum = 0;
for (let i = num; i > 0; i = Math.floor(i / 10)) {
sum += i % 10;
}
return sum;
}
console.log(sumOfDigitsForLoop(1234)); // Output: 10
Using for loop with string conversion
In this approach, we first convert the number to a string then loop through each character of the string and sum them.
function sumOfDigitsForLoopString(num) {
let sum = 0;
const str = num.toString();
for (let i = 0; i < str.length; i++) {
sum += parseInt(str[i]);
}
return sum;
}
console.log(sumOfDigitsForLoopString(1234)); // Output: 10
Using Array.reduce method
In this approach, we first convert the number into string then split them into digits, and finally use reduce to sum them.
function sumOfDigits(num) {
return num
.toString()
.split('')
.reduce((sum, digit) => sum + parseInt(digit), 0);
}
console.log(sumOfDigits(1234)); // Output: 10
Using recursion
You can use the recursion method where the function keeps calling itself until the number becomes 0.
function sumOfDigits(num) {
if (num === 0) return 0;
return (num % 10) + sumOfDigits(Math.floor(num / 10));
}
console.log(sumOfDigits(1234)); // Output: 10