Recursive product of all digits of a number - JavaScript


We are required to write a JavaScript function that takes in a number and finds the product of all of its digits. If any digit of the number is 0, then it should be considered and multiplied as 1.

For example − If the number is 5720, then the output should be 70

Example

Following is the code −

const num = 5720;
const recursiveProduct = (num, res = 1) => {
   if(num){
      return recursiveProduct(Math.floor(num / 10), res * (num % 10 || 1));
   }
   return res;
};
console.log(recursiveProduct(num));

Output

This will produce the following output in console −

70

Updated on: 18-Sep-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements