Categories
JavaScript Answers

How to sum all the digits of a number JavaScript?

Spread the love

Sometimes, we want to sum all the digits of a number JavaScript.

In this article, we’ll look at how to sum all the digits of a number JavaScript.

How to sum all the digits of a number JavaScript?

To sum all the digits of a number JavaScript, we can use some array methods.

For instance, we write:

const value = 2568;
const sum = value
  .toString()
  .split('')
  .map(Number)
  .reduce((a, b) => a + b, 0);
console.log(sum)

to split the value number into an array of digits.

And then we add the digits together with reduce.

To split the digits, we use toString to convert it to a string.

Then we call split with an empty string to split the string version of value into an array of digit strings.

Next, we call map with Number to map the digit strings back to numbers.

And then we use reduce to add them together.

Therefore, sum is 21.

Conclusion

To sum all the digits of a number JavaScript, we can use some array methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *