- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Digit sum upto a number of digits of a number in JavaScript

We are required to write a JavaScript function that takes in two numbers, let’s say m and n as arguments.

n will always be smaller than or equal to the number of digits present in m. The function should calculate and return the sum of first n digits of m.

For example −

If the input numbers are −

const m = 5465767; const n = 4;

Then the output should be −

const output = 20;

because 5 + 4 + 6 + 5 = 20

## Example

Following is the code −

const m = 5465767; const n = 4; const digitSumUpto = (m, n) => { if(n > String(m).length){ return 0; }; let sum = 0; for(let i = 0; i < n; i++){ const el = +String(m)[i]; sum += el; }; return sum; }; console.log(digitSumUpto(m, n));

## Output

Following is the console output −

20

- Related Articles
- Reduce sum of digits recursively down to a one-digit number JavaScript
- Prime digits sum of a number in JavaScript
- Finding sum of digits of a number until sum becomes single digit in C++
- C program to find sum of digits of a five digit number
- Product sum difference of digits of a number in JavaScript
- Summing up all the digits of a number until the sum is one digit in JavaScript
- C++ program to find sum of digits of a number until sum becomes single digit
- Recursive sum all the digits of a number JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Sum of the digits of a two digit number is 9. When we interchange the digits of the two digit number, the resultant number exceeds the original number by 27. Find the number.
- Check whether sum of digit of a number is Palindrome - JavaScript
- Difference between product and sum of digits of a number in JavaScript
- The difference of the digits of a two-digit number is 2. The sum of that two-digit number and the number obtained by interchanging the places of its digits is 132. Find the two-digit number(s).
- A two-digit number is 4 times the sum of its digits and twice the product of the digits. Find the number.
- A two digit number is 4 times the sum of its digits and twice the product of its digits. Find the number.

Advertisements