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

Updated on: 19-Jan-2021

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements