Find even odd index digit difference - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number and returns the difference of the sums of the digits at even place and the digits odd place

Example

Let’s write the code −

const num = 345336;
const evenOddDifference = (num, res = 0, ind = 0) => {
   if(num){
      if(ind % 2 === 0){
         res += num % 10;
      }else{
         res -= num % 10;
      };
   };
   return Math.abs(res);
};
console.log(evenOddDifference(num));

Output

Following is the output in the console −

2
raja
Published on 14-Sep-2020 17:15:44
Advertisements