How to multiply all numbers in an array using JavaScript

In this article, we will see how to multiply all the numbers in an array using JavaScript.

Let’s say we have an array of numbers like this,

[2,2,3,4]

And we have to multiply all the numbers and give us the product as the return value.

So the output should be:

Input: [2,2,3,4]
Output : 2*2*3*4 = 48

So using JavaScript, we will find the product of all the elements of an array using:

  1. for loop or
  2. Array.reduce() function.

    Let’s see each with an example.

Multiple numbers in an array using for loop

We can use the for loop in JavaScript to find the product of all the numbers in an array.

Example:

const arr = [2,2,3,4]

const multiply = (arr) => {
    var pro = 1;
    for (i = 0; i < arr.length; i++)
        pro = pro * arr[i];
    return pro;
}

 console.log(multiply(arr)) // Output : 48

Here, in the above code, we have created a function called multiply, which takes an array as an argument.

And the function uses for loop to loop through each element in the array until the condition i < arr.length is met.

On each iteration of the loop, the multiplied value is stored in the variable pro . And the initial value of pro is 1 , as any number multiple with 0 is 0.

Once, the condition is met(i.e false) it returns us the product of the multiplied numbers.

Multiply all the numbers in an array using reduce()

The reduce() method runs a user-defined “reducer” callback function on each element of an array. It returns a single value after running the callback function on each element of the array.

Syntax:

reduce(callbackFn, initialValue)

callBackFn: The user-specified “reducer” function.

initialValue: It is the value that is passed to the function as the initial value.

So, let’s use the Array.reduce() method to multiple numbers in an array.

const arr = [2,2,3,4]
const pro = arr.reduce((a, b)=> a*b, 1)

console.log(pro) // 48

Here, the initialValue is 1 and not 0, because any number multiple with 0 is 0.

And, (a, b) => a*b is the callback function.

Scroll to Top