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 loop
2function sumArray(arr) {
3 let sum = 0;
4 for (let i = 0; i < arr.length; i++) {
5 sum += arr[i];
6 }
7 return sum;
8}
9
10let numbers = [1, 2, 3, 4, 5];
11console.log("Array:", numbers);
12console.log("Sum:", sumArray(numbers));
13
14// Method 2: Using reduce
15function sumArrayReduce(arr) {
16 return arr.reduce((acc, num) => acc + num, 0);
17}
18
19console.log("\nUsing reduce:", sumArrayReduce([10, 20, 30]));
20
21// Method 3: Using forEach
22function sumArrayForEach(arr) {
23 let sum = 0;
24 arr.forEach(num => sum += num);
25 return sum;
26}
27
28console.log("\nUsing forEach:", sumArrayForEach([5, 10, 15]));
29
30// Method 4: Using for...of loop
31function sumArrayForOf(arr) {
32 let sum = 0;
33 for (let num of arr) {
34 sum += num;
35 }
36 return sum;
37}
38
39console.log("\nUsing for...of:", sumArrayForOf([2, 4, 6, 8]));
40
41// Method 5: One-liner
42const sum = arr => arr.reduce((a, b) => a + b, 0);
43
44console.log("\nOne-liner:", sum([1, 2, 3, 4, 5]));
45
46// 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}
51
52console.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.