JavaScript: Calculate the product of values in an array
JavaScript Math: Exercise-18 with Solution
Product of Array Values
Write a JavaScript function to calculate the product of values in an array.
Test Data:
console.log(product([1,2,3]));
console.log(product([100,-200,3]));
console.log(product([1,2,'a',3]));
Output:
6
-60000
6
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named sum that calculates the sum of an array of numbers.
function sum(input){
// Check if the input is an array, if not, return false.
if (toString.call(input) !== "[object Array]")
return false;
var total = 0;
// Iterate through the input array and sum the numeric elements.
for(var i = 0; i < input.length; i++) {
// If the element is not a number, skip to the next element.
if(isNaN(input[i])){
continue;
}
// Add the numeric value of the element to the total.
total += Number(input[i]);
}
// Return the total sum.
return total;
}
// Output the sum of the numbers in the array [1, 2, 3] to the console.
console.log(sum([1, 2, 3]));
// Output the sum of the numbers in the array [100, -200, 3] to the console.
console.log(sum([100, -200, 3]));
// Output the sum of the numbers in the array [1, 2, 'a', 3] to the console.
console.log(sum([1, 2, 'a', 3]));
Output:
6 -60000 6
Flowchart:
Live Demo:
See the Pen javascript-math-exercise-18 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to calculate the sum of values in an array.
Next: Create a Pythagorean function in JavaScript
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics