Example 1 — Sum of Digits (Fixed Number)
Use % 10 and Math.floor until the number becomes zero.
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
Math.abskeeps the helper safe for negatives.- Each loop takes the last digit with
number % 10. Math.floor(number / 10)drops that digit for the next pass.- For
12345the digits added are 5, 4, 3, 2, then 1. - When
numberhits0, return15.
