Finding product of Number digits in JavaScript

We are required to write a JavaScript program that takes in a number and finds the product of all of its digits.

Input Output Scenarios

Here are examples of finding the product of number digits:

Input = 12345
Output = 120 (1 × 2 × 3 × 4 × 5 = 120)

We can also work with string numbers and convert them to integers:

Input = "12345"
Output = 120

Using Math.floor() and Modulo Operator

The Math.floor() function returns the largest integer less than or equal to a given number. We use it to remove the last digit by dividing by 10.

Syntax

Math.floor(x)

Example: Product of Number Digits

This approach uses Math.floor() to extract each digit and multiply them:

<!DOCTYPE html>
<html>
<head>
   <title>Product of Number Digits</title>
</head>
<body>
   <p id="result"></p>
   <script>
      let num = 12345;
      let product = 1;
      
      while (num != 0) {
         product = product * (num % 10);
         num = Math.floor(num / 10);
      }
      
      document.getElementById("result").innerHTML = "The product of digits is: " + product;
   </script>
</body>
</html>
The product of digits is: 120

Using parseInt() with String Conversion

The parseInt() function parses a string argument and returns an integer value.

Syntax

parseInt(string)

Example: Converting String to Integer

This method converts the number to a string, then iterates through each character:

<!DOCTYPE html>
<html>
<head>
   <title>Product of Number Digits</title>
</head>
<body>
   <button onclick="calculateProduct()">Calculate Product</button>
   <p id="output"></p>
   
   <script>
      function calculateProduct() {
         let numberStr = "12345";
         let product = 1;
         
         for (let i = 0; i < numberStr.length; i++) {
            product = product * parseInt(numberStr[i]);
         }
         
         document.getElementById("output").innerHTML = "Product: " + product;
      }
   </script>
</body>
</html>
Product: 120

Using Array Methods

A more modern approach using array methods:

function getDigitProduct(num) {
   return num.toString()
             .split('')
             .map(Number)
             .reduce((product, digit) => product * digit, 1);
}

console.log(getDigitProduct(12345)); // 120
console.log(getDigitProduct(987));   // 504
120
504

Comparison of Methods

Method Input Type Performance Readability
Math.floor() + Modulo Number Fast Medium
parseInt() + Loop String/Number Medium Good
Array Methods Number Slower Excellent

Conclusion

All three methods effectively calculate the product of number digits. Choose the Math.floor() approach for performance, or array methods for cleaner, more readable code.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements