w3resource

JavaScript: Calculate the sum of values in an array

JavaScript Math: Exercise-17 with Solution

Write a JavaScript function to calculate the sum of values in an array.

Test Data :
console.log(sum([1,2,3]));
console.log(sum([100,-200,3]));
console.log(sum([1,2,'a',3]));
Output :
6
-97
6

Visual Presentation:

JavaScript: Math - Calculate the sum of values in an array.

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
-97
6

Flowchart:

Flowchart: JavaScript Math- Calculate the sum of values in an array

Live Demo:

See the Pen javascript-math-exercise-17 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to check whether a variable is numeric or not.
Next: Write a JavaScript function to calculate the product of values in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.