To sum all digits of a number in JavaScript, you can use a function that takes a number as an input and returns the sum of its digits. One possible way to implement this function is:
JavaScriptAI-generated code. Review and use carefully.
function sumDigits(num) {
// Convert the number to a string
let numStr = num.toString();
// Initialize a variable to store the sum
let sum = 0;
// Loop through each character of the string
for (let i = 0; i < numStr.length; i++) {
// Convert the character to a number and add it to the sum
sum += Number(numStr[i]);
}
// Return the sum
return sum;
}
Here is an example of using this function:
JavaScriptAI-generated code. Review and use carefully. More info on FAQ.
// Test the function with a number
let num = 1234;
// Call the function and store the result
let result = sumDigits(num);
// Print the result
console.log("The sum of digits of " + num + " is " + result);
// Output: The sum of digits of 1234 is 10