JavaScript: 3 Ways to Find the Product of a Numeric Array

Updated: May 25, 2023 By: Wolf Post a comment

The product of a numeric array is the result of multiplying all the numbers within the array together. For example, the product of the array [1, 2, 3] is 6, and the product of the array [2, 2] is 4.

This succinct, example-based article gives you a bunch of different ways to calculate the product of a numeric array in JavaScript. Without any further ado, let’s explore them one by one.

Using the reduce() method

This approach can be summarized as follows:

  • Use the reduce() method on the array to iteratively multiply the elements together.
  • Initialize the accumulator value to 1.
  • Multiply each element of the array with the accumulator value in each iteration.
  • Return the final accumulated product.

Example:

const calculateProduct = (arr) => {
  if (arr.length === 0) {
    return 0; // Assuming the product of an empty array is 0
  }

  const product = arr.reduce(
    (accumulator, currentValue) => accumulator * currentValue
  );

  return product;
};

const numbers = [2, 3, 4, 5];
const result = calculateProduct(numbers);

console.log(result); // Output: 120 (2 * 3 * 4 * 5)

Our code assumes the product of an empty array is 0. You can adjust this behavior based on your specific requirements.

Using a for…of loop

This is a four-step process:

  • Initialize a variable to hold the product and set it to 1.
  • Iterate over each element in the array using a for…of loop.
  • Multiply each element with the product variable in each iteration.
  • Return the final calculated product.

Example:

const calculateProduct = (arr) => {
  if (arr.length === 0) {
    return 0; // Assuming the product of an empty array is 0
  }

  let product = 1;

  for (const num of arr) {
    product *= num;
  }

  return product;
}

const numbers = [4, 5, 6, 7];
const result = calculateProduct(numbers);

console.log(result); // Output: 840 (4 * 5 * 6 * 7)

Using recursion

Explanation:

  • Define a recursive function that takes an array and an index as parameters.
  • Base Case: If the index is equal to the array length, return 1 (indicating the end of recursion).
  • Recursive Case: Multiply the current element at the given index with the product of the remaining array elements.
  • Call the recursive function with the updated index and return the result.

Example:

const calculateProductRecursive = (arr, index = 0) => {
  if (index === arr.length) {
    return 1;
  }

  return arr[index] * calculateProductRecursive(arr, index + 1);
}

const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1];
const result = calculateProductRecursive(numbers);

console.log(result); // Output: 362880 

This solution is concise, and no explicit looping constructs are used. However, the recursive implementation may have performance implications for large arrays.