Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Multiply All

Exercise 24 Very easy

Prerequisites for the exercise

  1. JavaScript for Loop
  2. All previous chapters

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]);
-350
multiplyAll([2, 2, 2]);
8
multiplyAll([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
3628800
multiplyAll([]);
null
View Solution

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;
}