Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to find the sum of an array of numbers in JavaScript?

Answer: Using reduce() method

The reduce() method is used to calculate the sum of all the elements of an array. This method executes a reducer function for each value of an array.

The reduce() method returns the single value that is the sum of all the elements present within an array.

This method does execute the reducer function for the empty array elements, and also it does not change the original array.

Example: Using reduce() method

In the given example, we have calculated the sum of all the values within the array using the reduce() method.

<!DOCTYPE html>
<html lang="en">
<head>
	<title> find the sum of an array of numbers </title>
</head>
	<script>
	    var marks = [94, 76, 54, 61, 87];	    
	    var total = marks.reduce(function(x, y){
	        return x + y;
	    }, 0);
	    console.log(total); 
	</script>
</body>
</html>

Output


372

The 0 specified within the reduce() function is the initial value. This value can be used as the first argument to the first call of the callback function. If no initial value is specified then the first array value is used.

If the array is empty and no initial value is specified then it will through an error.

Another method apart from reduce() method is using for loop. We can also calculate the sum of values of an array using for loop. This method is as fast as the reduce() method.

Example: Using for loop

In the given example, we have calculated the sum of array values using for loop.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>find the sum of an array of numbers </title>
</head>
	<script>
		let marks = [94, 76, 54, 61, 87]
		let total = 0;
		for (let i = 0; i < marks.length; i++) {
		total += marks[i]
		}
		console.log(total) 
	</script>
</body>
</html>

Output


372

Conclusion

Here, we have discussed how to find the sum of an array of numbers in JavaScript. There are several ways to find the sum of an array of numbers, but in this lesson, we have covered the most used and easy methods. So first, we have calculated the sum of array values using the reduce() method, which is the predefined JS method, and the second one is using for loop.



About the author: