Sum all the Digits in a Number using JavaScript


Borislav Hadzhiev

Fri Oct 22 20212 min read


Photo by Levi Morsy

Sum all the Digits in a Number using JavaScript #

To sum all of the digits in a number:

  1. Convert the number to a string and use the split() method to split it into an array of strings.
  2. Call the reduce() method on the array and sum the accumulator with each array element converted back to a number.
function getSumOfDigits(num) { return String(num) .split('') .reduce((acc, curr) => { return acc + Number(curr); }, 0); } console.log(getSumOfDigits(1)); // 👉️ 1 console.log(getSumOfDigits(123)); // 👉️ 6 console.log(getSumOfDigits(1234)); // 👉️ 10

We created a reusable functions to get the sum of all digits in a number.

The first thing we do is convert the number to a string, using the String object.

We then call the String.split method on the string to get an array containing the digits as elements.

console.log('1'.split('')); // 👉️ ['1'] console.log('123'.split('')); // 👉️ ['1', '2', '3'] console.log('1234'.split('')); // 👉️ ['1', '2', '3', '4']
The parameter we passed to the split method is a separator (on which character we want to split the string). Because we want each digit to be its own array element we supplied an empty string.

The last step is to use the Array.reduce method on the array of strings.

The function we passed to the reduce method gets called with each element (string) in the array.

The second parameter we passed to the method is the initial value for the acc (accumulator) variable.

On each iteration we return the sum of the current accumulator and the current array element casted back to a number to get the value for the acc variable for the next iteration.

Once the reduce method iterates over the entire array, we have the sum of all the digits in the number.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.