• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / JavaScript / Sum the Digits of a Number in JavaScript

Sum the Digits of a Number in JavaScript

May 9, 2022 Leave a Comment

To sum the digits of a number in JavaScript, we can use a for loop which will get each digit from the number and add them together. Here is a quick function that will take a number and then sum it’s digits:

function sumDigits(num){
  var sum = 0;
  var numString = num + "";
  for ( var i = 0; i < numString.length; i++ ){
    sum = sum + Number(numString.charAt(i));
  };
  return sum;
}

Let’s break down this function line by line.


In our sumDigits() function, we first start out by creating a variable that we will use to help sum up all the numbers, called sum.

We next convert the number into a string.

We then use a for loop to loop through all of the digits in the number. In this for loop, we use the charAt() method to help iterate over each digit in the number. We then add that number to our overall sum.

Finally, we return the value of the sum of the digits of the number.

Let’s see this function in action below.

Sum the Digits of a Number in JavaScript With a Click

To sum up the digits of a number on click using JavaScript, we can combine the function sumDigits() we created above with a click event.

Below we will provide code to let the user input a number, and then use our function to return the results. Here is our simple HTML setup:

<p>Type a number you want to sum the digits of:</p>
<input id="userVal" type="text" value="" onkeyup="sumDigits(event)">
<input id="submitNum" type="submit" value="Submit" onclick="sumDigits('click')">
<div id="results"></div>

Below is the JavaScript code which take the user input using the onkeyup event or the onclick event along with the value property and use our function sumDigits() on that user input and update the results below using the textContent property.

Here is the JavaScript code:

function sumDigits(e) {
  //If we clicked or pressed enter, run the following code 
  if( e == 'click' || e.keyCode == 13 ){
    //Get the number the user entered
    var userNum = document.getElementById("userVal").value;

    //Use code from our function above
    var sum = 0;
    var numString = userNum + "";
    for ( var i = 0; i < numString.length; i++ ){
      sum = sum + Number(numString.charAt(i));
    };

    //Show the result to the user to the user
    document.getElementById("results").textContent = sum;   
  }
};

The final code and output for this example are below:

Code Output:

Type a number you want to sum the digits of:


Full Code:

<p>Type a number you want to sum the digits of:</p>
<input id="userVal" type="text" value="" onkeyup="sumDigits(event)">
<input id="submitNum" type="submit" value="Submit" onclick="sumDigits('click')">
<div id="results"></div>

<script>

function sumDigits(e) {
  if( e == 'click' || e.keyCode == 13 ){
    var userNum = document.getElementById("userVal").value;
    var sum = 0;
    var numString = userNum + "";
    for ( var i = 0; i < numString.length; i++ ){
      sum = sum + Number(numString.charAt(i));
    };
    document.getElementById("results").textContent = sum;   
  }
};

</script>

Hopefully this article has been useful in helping you understand how to sum up the digits of a number in JavaScript.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to Get URL Hash
  • 2.  How to Convert Radians to Degrees Using JavaScript
  • 3.  JavaScript String endsWith Method
  • 4.  Get the First Child Element and Change it with JavaScript
  • 5.  How to Use JavaScript to Check if a String is Empty
  • 6.  Using JavaScript to Capitalize the First Letter of a String
  • 7.  Loop Through an Array of Objects in JavaScript
  • 8.  How to Count Vowels in a String Using JavaScript
  • 9.  JavaScript atan – Find Arctangent and Inverse Tangent of Number
  • 10.  JavaScript Infinite Loop

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy