Objective
Create a function to multiply all the numbers in a given array and return the product.
Description
Consider the following array of numbers:
var nums = [1, 5, 70, -2, -1, -0.5];
If we multiply all the numbers together, we get the value -350
.
In this exercise, you ought to create a function multiplyAll()
that takes in an array of numbers and returns back their product.
If the array is empty, the value returned should be null
.
Here are some examples of the usage of the function:
multiplyAll([1, 5, 70, -2, -1, -0.5]);
multiplyAll([2, 2, 2]);
multiplyAll([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
multiplyAll([]);
New file
Inside the directory you created for this course on JavaScript, create a new folder called Exercise-24-Multiply-All and put the .html solution files for this exercise within it.
Solution
To start with, we'll deal with the special case, i.e. when the given array is empty, where we have to return null
:
function multiplyAll(arr) {
if (arr.length === 0) {
return null;
}
}
Proceeding forward, we lay out a variable product
to hold the product of itself and the current number during each iteration of the loop.
In the end, this variable effectively holds the product of all the numbers in the array.
Altogether, we get to the following code:
function multiplyAll(arr) {
if (arr.length === 0) {
return null;
}
var product = 1;
for (var i = 0; i < arr.length; i++) {
product *= arr[i];
}
return product;
}