Sum all the Digits in a Number using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

Sum all the Digits in a Number using JavaScript #

To sum all the digits in a number:

  1. Convert the number to a string.
  2. Use the split() method to split the string into an array of digits.
  3. Use the reduce() method to sum all the digits in the array.
index.js
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 that returns the sum of the digits in a number.

We used the String object to convert the number to a string.

We then called the String.split method on the string to get an array of digits.

index.js
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). We want each digit to be its own array element, so we supplied an empty string.

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

index.js
function getSumOfDigits(num) { return String(num) .split('') .reduce((acc, curr) => { return acc + Number(curr); }, 0); } console.log(getSumOfDigits(5)); // 👉️ 5 console.log(getSumOfDigits(55)); // 👉️ 10 console.log(getSumOfDigits(555)); // 👉️ 15

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 converted back to a number. Whatever we return from the callback function gets passed as the accumulator on 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.