There are multiple approaches to finding the sum of an array of numbers in JavaScript.
1. Using for Loop
The for
loop is a basic and widely used approach to sum the elements of an array. Initialize a variable to store the sum and iterate through the array, adding each element to the sum.
let arr = [10, 20, 30, 40, 50]; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } console.log(sum); // Output: 150
2. Using for…of Loop
The for...of
loop, introduced in ES6, simplifies iterating over array elements without needing to manage indices.
let arr = [10, 20, 30, 40, 50]; let sum = 0; for (let num of arr) { sum += num; } console.log(sum); // Output: 150
3. Using reduce() Method
The reduce()
method is a powerful functional programming approach to accumulate values in an array, making it ideal for calculating sums.
let arr = [10, 20, 30, 40, 50]; let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 150
4. Using forEach() Method
The forEach()
method iterates over each element of the array and allows you to update an external variable.
let arr = [10, 20, 30, 40, 50]; let sum = 0; arr.forEach(num => { sum += num; }); console.log(sum); // Output: 150
5. Using eval() Method (Not Recommended)
You can convert the array to a string and use eval()
method to compute the sum. However, this method is not recommended due to security and readability issues.
let arr = [10, 20, 30, 40, 50]; let sum = eval(arr.join('+')); console.log(sum); // Output: 150
7. Using Recursion
You can calculate the sum of an array recursively, although it’s less efficient for large arrays.
function sumArray(arr) { if (arr.length === 0) return 0; // Base case return arr[0] + sumArray(arr.slice(1)); // Recursive case } let arr = [10, 20, 30, 40, 50]; console.log(sumArray(arr)); // Output: 150
8. Using Lodash _.sum() Method
If you’re already using Lodash in your project, the _.sum()
method provides a simple way to sum array elements.
const _ = require('lodash'); let arr = [10, 20, 30, 40, 50]; let sum = _.sum(arr); console.log(sum); // Output: 15