OneBite.Dev - Coding blog in a bite size

find the product of all elements in an array in Javascript

Code snippet on how to find the product of all elements in an array in Javascript

  var myArray = [4, 8, 15, 16, 23, 42];
  var product = myArray.reduce(function(acc, val) {
    return acc * val;
  });

This code first declares a variable named myArray and stores a series of numbers in it. It then creates a variable named product which uses the reduce() method on myArray. The reduce() method will take each value in myArray, and perform the function defined in the code on that value and the current accumulative value (acc). In this case, the function performs a multiplication operation on each value, and stores the result in the product variable. When the loop is finished, the product variable contains the product of all elements in the array.

javascript