Sum of Array Elements in JavaScript
reduce from 0. Forget the 0 and an empty array throws.
BeginnerArray ProgramsExample 3 of 6
sum-of-array-elements.js
1// Method 1: Using for loop2function sumArray(arr) {3 let sum = 0;4 for (let i = 0; i < arr.length; i++) {5 sum += arr[i];6 }7 return sum;8}910let numbers = [1, 2, 3, 4, 5];11console.log("Array:", numbers);12console.log("Sum:", sumArray(numbers));1314// Method 2: Using reduce15function sumArrayReduce(arr) {16 return arr.reduce((acc, num) => acc + num, 0);17}1819console.log("\nUsing reduce:", sumArrayReduce([10, 20, 30]));2021// Method 3: Using forEach22function sumArrayForEach(arr) {23 let sum = 0;24 arr.forEach(num => sum += num);25 return sum;26}2728console.log("\nUsing forEach:", sumArrayForEach([5, 10, 15]));2930// Method 4: Using for...of loop31function sumArrayForOf(arr) {32 let sum = 0;33 for (let num of arr) {34 sum += num;35 }36 return sum;37}3839console.log("\nUsing for...of:", sumArrayForOf([2, 4, 6, 8]));4041// Method 5: One-liner42const sum = arr => arr.reduce((a, b) => a + b, 0);4344console.log("\nOne-liner:", sum([1, 2, 3, 4, 5]));4546// Method 6: Sum with condition (even numbers only)47function sumEvenNumbers(arr) {48 return arr.filter(num => num % 2 === 0)49 .reduce((acc, num) => acc + num, 0);50}5152console.log("\nSum of even numbers:", sumEvenNumbers([1, 2, 3, 4, 5, 6]));
Output
Array: [ 1, 2, 3, 4, 5 ] Sum: 15 Using reduce: 60 Using forEach: 30 Using for...of: 20 One-liner: 15 Sum of even numbers: 12
What's going on
reduce((a, b) => a + b, 0). Skip the 0 and reduce on [] throws. The 0 is not decoration.