Write a function that takes a number as input and returns the sum of its digits. For example, if the input number is 123, the function should return 6 (1 + 2 + 3 = 6).
function sumDigits(num) {
let sum = 0;
// Convert the number to a string so we can loop over its digits
const numStr = num.toString();
// Loop over each digit in the string and add it to the sum
for (let i = 0; i < numStr.length; i++) {
sum += parseInt(numStr[i]);
}
// Return the final sum
return sum;
}
The function takes a single argument num
, which is the number to sum the digits of. Here’s what the function does:
sum
to 0, which will hold the running total of the digit sums.toString()
method. This allows us to loop over its individual digits.for
loop. For each digit, it converts the digit back to a number using parseInt()
and adds it to the sum
variable.sum
.Here’s an example usage of the function:
console.log(sumDigits(123)); // 6
console.log(sumDigits(456)); // 15
console.log(sumDigits(789)); // 24
In this example, the function correctly sums the digits of each input number and returns the correct result.