Calculate the sum of all array elements in JavaScript
This post will discuss how to calculate the sum of all array elements in JavaScript.
There are several ways to get the sum of all elements of an array in JavaScript, depending on the performance, readability, and compatibility of the code. Here are some of the functions that we can use, along with some examples:
1. Using a for loop
This is a straightforward and intuitive way to iterate over the array and add each element to a variable that stores the sum. Here’s an example:
|
1 2 3 4 5 6 7 8 9 |
let arr = [1, 2, 3, 4]; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } console.log("Sum is " + sum); // Sum is 10 |
This function is compatible with older browsers, but it may not be very elegant or concise.
2. Using forEach() function
The forEach() function allows us to iterate over each element of the array and perform an operation. We can use it to calculate the sum of all elements. Here’s an example:
|
1 2 3 4 5 6 7 8 |
let arr = [1, 2, 3, 4]; let sum = 0; arr.forEach((element) => { sum += element; }); console.log("Sum is " + sum); // Sum is 10 |
This function is more functional and expressive than loops, but it may have some performance overhead and compatibility issues.
3. Using reduce() function
The reduce() function takes a callback function that accumulates the value of each element in the array and returns the final result. This is a concise and functional way to calculate the sum, but it requires an initial value to avoid errors when the array is empty. Here’s an example:
|
1 2 3 4 |
let arr = [1, 2, 3, 4]; let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log("Sum is " + sum); // Sum is 10 |
This function is simple and elegant, but it requires ES6 support or a polyfill for older browsers.
That’s all about calculating the sum of all array elements in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)