How to get sum of all digits of a number in JavaScript
In this tutorial, we are going to learn about how to get the sum of the all digits of a number in JavaScript.
Consider, we have a following the JavaScript code like this:
const total = 234;
Now, we need to count the sum of 2+3+4 and return the output 9;
Getting the sum of all digits
To get the sum of all digits in a number, first we need to convert the given number to a string, then we need to use the combination of split() and reduce() methods.
The split() method takes the string as an argument and splits it into an array of individual elements.
The reduce() method takes the array as an argument and returns the sum of it.
Here is an example:
const total = 234;
const totalString = String(total);
const sum = totalString.split('').reduce((acc, digit) => acc+Number(digit),0);
console.log(sum);
Output:
9
Sum of all digits of a number using for-of loop
To get sum of all digits of a number using for-of loop:
-
Initialize the sum variable with 0.
-
Convert the number to a string using the String() constructor.
-
On each iteration convert the string back to a number and sum all digits of a number.
Here is an example:
const a = String(234);
let sum = 0;
for (let n of a){
sum += Number(n);
}
console.log(sum);
Output:
9