Author -  Sai gowtham

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:

  1. Initialize the sum variable with 0.

  2. Convert the number to a string using the String() constructor.

  3. 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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY