JavaScript
// Method 1: Using for loop
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
let numbers = [1, 2, 3, 4, 5];
console.log("Array:", numbers);
console.log("Sum:", sumArray(numbers));
// Method 2: Using reduce
function sumArrayReduce(arr) {
return arr.reduce((acc, num) => acc + num, 0);
}
console.log("\nUsing reduce:", sumArrayReduce([10, 20, 30]));
// Method 3: Using forEach
function sumArrayForEach(arr) {
let sum = 0;
arr.forEach(num => sum += num);
return sum;
}
console.log("\nUsing forEach:", sumArrayForEach([5, 10, 15]));
// Method 4: Using for...of loop
function sumArrayForOf(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
}
console.log("\nUsing for...of:", sumArrayForOf([2, 4, 6, 8]));
// Method 5: One-liner
const sum = arr => arr.reduce((a, b) => a + b, 0);
console.log("\nOne-liner:", sum([1, 2, 3, 4, 5]));
// Method 6: Sum with condition (even numbers only)
function sumEvenNumbers(arr) {
return arr.filter(num => num % 2 === 0)
.reduce((acc, num) => acc + num, 0);
}
console.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
This program demonstrates different methods to sum array elements.
Method 1: For Loop
Traditional approach:
javascriptlet sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; }
Method 2: Reduce
Most common modern approach:
javascriptarr.reduce((acc, num) => acc + num, 0);
Initial Value:
0is the starting accumulator value- Important for empty arrays
Method 3: ForEach
Functional iteration:
javascriptlet sum = 0; arr.forEach(num => sum += num);
Method 4: For...Of Loop
ES6 iteration:
javascriptfor (let num of arr) { sum += num; }
For...Of vs For Loop:
- For...of: Cleaner, works with any iterable
- For loop: More control, index access
Method 5: Arrow Function
One-liner:
javascriptconst sum = arr => arr.reduce((a, b) => a + b, 0);
Method 6: Conditional Sum
Sum only even numbers:
javascriptarr.filter(num => num % 2 === 0) .reduce((acc, num) => acc + num, 0);
Chaining Methods:
filter(): Creates new array with matching elementsreduce(): Sums filtered array
Performance:
- All methods: O(n) time complexity
- Reduce: Slightly more efficient (single pass)
When to Use:
-
Reduce: Most common, functional
-
For loop: Learning, custom logic
-
For...of: Clean iteration
-
One-liner: Quick calculations