How To Find The Sum Of An Array Of Numbers in JavaScript – Definitive Guide

The Array objects help store a collection of multiple items under a single variable name and provide various functions for manipulating the array values.

You can use the array.reduce() method to find the sum of an array of numbers in JavaScript

Using reduce (Quick Solution)

To find the sum of an array of numbers in JavaScript:

  • You can use the array.reduce() method, which iterates through each array element and adds the current value to the previous value.
  • Set the initial value of reduce to 0, so the previous value will start with 0.

Code

    const prices = [100, 200, 300, 400];
    const totalPriceAmount = prices.reduce((previous, current) => previous + current, 0);
    console.log(totalPriceAmount);

Output

    1000

The reduce() method iterates through the element and adds the current value to the previous value. Initially, the previous value will be assigned with 0; later, it gets updated after each addition and returns the total sum.

Using ForEach

You can also use simple ForEach to find the sum of an array of numbers

  • Set a variable to hold the total sum(let totalPriceAmount = 0).
  • Iterate the array using the forEach method.
  • Add the current value to the total sum variable and retains the new value.

Code

    const prices = [100, 200, 300, 400];
    let totalPriceAmount = 0;
    prices.forEach(price => {
        totalPriceAmount += price
    })
    console.log(totalPriceAmount);

Output

    1000

The array is iterated using forEachand the current element is added to the totalPriceAmount variable.

ES6 for…of

The for...of statement creates a loop iterating over like string, array.
To hold the total sum, you can add the current iterated value to a variable.
Code

    const prices = [100, 200, 300, 400];
    let totalPriceAmount = 0;
    for (let value of prices) {
        totalPriceAmount += value;
    }
    console.log(totalPriceAmount);

Output

    1000

Using For Loop

You can also use a simple for loop to iterate through a simple for loop and get the current value added to a variable.
Code

    const prices = [100, 200, 300, 400];
    let totalPriceAmount = 0;
    for (var i = 0; i < prices.length; i++) {
        totalPriceAmount += prices[i];
    }
    console.log(totalPriceAmount);

Output

    1000

Using While Loop

A while loop execution will also help to iterate through an array, add the current value to a variable, and get the total sum of an array.
Code

    const prices = [100, 200, 300, 400];
    let totalPriceAmount = 0,
    i = -1;
    while (++i < prices.length) {
        totalPriceAmount += prices[i];
    }
    console.log(totalPriceAmount);

Output

    1000

Live Demo

Related Topics

Leave a Comment