Sum of an Array in JavaScript
Last Updated :
16 Apr, 2025
There are multiple ways to calculate the sum of elements in an array in JavaScript. Here are some of the most common methods:
1. Using for loop (Simple for all Array)
A basic and straightforward way to sum the elements of an array is by using a for loop. This method iterates through each element in the array, adding it to a cumulative sum.
JavaScript
let a = [4, 8, 7, 13, 12]
let sum = 0;
for (let i = 0; i < a.length; i++) {
sum += a[i];
}
console.log(sum)
- The loop goes through each element of the array.
- Each element is added to the sum variable on each iteration.
2. Using forEach() Method
forEach() method is a built-in method that allows you to run a function on each element in the array. You can use it to add up the numbers.
JavaScript
let a = [4, 8, 7, 13, 12]
let sum = 0;
a.forEach(x => {
sum += x;
});
console.log(sum);
- forEach() runs the function for each item in the array.
- The function adds each number to sum.
3. Using reduce() Method
We are going to use the JavaScript reduce() method to find the sum of the array. reduce() is a more elegant way to sum up array elements. It works by processing all the array elements and combining them into a single value.
JavaScript
let a = [4, 8, 7, 13, 12]
let sum = a.reduce(function (x, y) {
return x + y;
}, 0);
console.log(sum);
- reduce() starts with an initial value (0) and adds each element to it.
- It returns the final sum after processing all the elements.
4. Using Recursion
Recursion means a function calling itself until a condition is met. Here, the function adds elements until it reaches the end of the array.
JavaScript
let a = [4, 8, 7, 13, 12];
function sumArray(a, idx) {
if (idx === a.length) {
return 0;
}
return a[idx] + sumArray(a, idx + 1);
}
console.log(sumArray(a, 0));
- The function keeps calling itself with the next index.
- When it reaches the end, it returns 0, and the values are added back together.
5. UsingLodash _.sum() Method
In this approach, we are using the Lodash _.sum() method for getting the sum of all element of an array.
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// Use of _.sum () method
let sum = _.sum([5, 10, 15, 20, 25]);
console.log(sum);
- _.sum() automatically adds up all the numbers in the array and returns the sum.
6. Using the eval Function
The eval Function approach calculates the sum of an array by converting it to a string with elements joined by '+', then using eval to evaluate the string as a JavaScript expression, returning the sum.
JavaScript
const sum = a => eval(a.join('+'));
const a = [1, 2, 3, 4, 5];
console.log(sum(a));
- The array is joined into a string like "1+2+3+4+5".
- eval() runs the string as a math expression and returns the sum.
Note: This method can be dangerous because eval() can execute any code in the string.
7. Using the map() Method with reduce()
While map() is usually for transforming data, you can combine it with reduce() to sum the elements. However, it’s a bit less efficient because it creates a new array.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let sumUsingMap = numbers.map(num => num).reduce((acc, curr) => acc + curr, 0);
console.log(sumUsingMap);
- map() creates a new array with the same elements.
- reduce() then sums up the values of the new array.
Conclusion
If you're a beginner and come from another programming language, the simple for loop is a good choice because it’s easy to understand. But if you're working with JavaScript, it's helpful to know methods like map(), reduce(), and forEach(). These methods are more efficient and make your code cleaner, which is important as you get more comfortable with JavaScript.
Similar Reads
How to Add Elements to a JavaScript Array? Here are different ways to add elements to an array in JavaScript.1. Using push() MethodThe push() method adds one or more elements to the end of an array and returns the new length of the array.Syntaxarray.push( element1, element2, . . ., elementN );JavaScriptconst arr = [10, 20, 30, 40]; arr.push(
3 min read
Create an Array of Given Size in JavaScript The basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values.Syntaxconst arr = new Array( length );J
3 min read
Insert at the Beginning of an Array in JavaScript Following are different ways to add new elements at the beginning of an array1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Remove Elements From a JavaScript Array Here are the various methods to remove elements from a JavaScript ArrayRemove elements from Array1. Using pop() methodThe pop() method removes and returns the last element of an array. This function decreases the length of the array by 1 every time the element is removed.javascriptlet a = ["Apple",
6 min read
Remove Duplicate Elements from JavaScript Array To Remove the elements from an array we can use the JavaScript set method. Removing duplicate elements requires checking if the element is present more than one time in the array. 1. Using JavaScript Set() - Mostly UsedThe JavaScript Set() method creates an object containing only unique values. To r
3 min read
How to Remove Multiple Elements from Array in JavaScript? Here are various methods to remove multiple elements from an array in JavaScript1. Using filter() MethodThe filter() method creates a new array with the elements that pass the condition. This method does not change the original array.JavaScriptlet a = [1, 2, 3, 4, 5]; let remove = [2, 4]; a = a.filt
3 min read
Insert at the Beginning of an Array in JavaScript Following are different ways to add new elements at the beginning of an array1. Using the Array unshift() Method - Most Used:Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element
2 min read
Reverse an Array in JavaScript Here are the different methods to reverse an array in JavaScript1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array.JavaScriptlet a = [1, 2, 3
3 min read
JavaScript - Delete last Occurrence from JS Array These are the following ways to remove the last Item from the given array: 1. Using pop() Method (Simple and Easiest Method for Any Array) The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array. JavaScriptlet a = [34, 2
2 min read
Remove Empty Elements from an Array in JavaScript Here are different approaches to remove empty elements from an Array in JavaScript.1. Using array.filter() MethodThe array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions.array.filter( callback( element, index, arr ), thisValue )J
3 min read