- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements