Open In App

How to Find the Sum of an Array of Numbers in JavaScript ?

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
5 Likes
Like
Report

To find the sum of an array of numbers in JavaScript, you can use several different methods.

1. Using Array reduce() Method

The array reduce() method can be used to find the sum of array. It executes the provided code for all the elements and returns a single output.

Syntax

arr.reduce( callback( acc, element, index, array ) , acc )
// Given array
let a = [ 10, 20, 30, 40, 50 ];

// Calculate the sum using array.reduce()
let sum = a.reduce( (acc,e ) => acc + e , 0)

// Display the final Output
console.log("Sum of Array Elements: ", sum);

Output
Sum of Array Elements:  150

2. Using for Loop

We can also use for loop to find the sum of array elements. The for loop repeatedly executes a block of code as long as a specified condition is true.

Syntax

for ( Initialization ; condition ; increment){
// Code to be executed...
}
// Given array
let a = [10, 20, 30, 40, 50];

// Initialize sum variable
let sum = 0;

// Iterate using for loop
for (let i = 0; i < a.length; i++) {

	// Add to the number in each iteration
    sum += a[i];
}

// Display the final output
console.log("Sum of Array Elements: ", sum);

Output
Sum of Array Elements:  150

Time complexity: O(N)
Space complexity: O(1)

3. Using eval() and join() Methods

The eval() method is used to evaluate the expression string and array.join() method is used to create string from the array elements.

Syntax

eval(string);
// Given an Array
let a = [10, 20, 30, 40, 50];

// Use eval to calculate the sum
let sum = eval(a.join('+'));

// Display the final output
console.log("Sum of Array Elements: ", sum);

Output
Sum of Array Elements:  150

Using forEach() Method

The forEach() loop is used to iterate over the array and find the sum of array elements.

Syntax

array.forEach( callback(element, index, arr ), thisValue );
// Given array
let a = [10, 20, 30, 40, 50];

// Initialize sum variable
let sum = 0;

// Calculate the sum using forEach loop
a.forEach( e => sum += e );

// Display the final output
console.log("Sum of Array Elements: ", sum);

Output
Sum of Array Elements:  150

Article Tags :

Similar Reads