How to multiply all numbers in an array using JavaScript

featured Image

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.

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more