The user wants a JavaScript function to calculate the sum of all numbers in an array. I'll provide a few different approaches to accomplish this task.
- Using a for loop - traditional approach
- Using forEach method
- Using reduce method - most elegant/functional approach
- Using a for...of loop
Let me write clear examples with explanations. # JavaScript Function to Sum Array Numbers
Here are several ways to calculate the sum of all numbers in an array:
Method 1: Using reduce() (Recommended)
function sumArray(numbers) {
return numbers.reduce((accumulator, current) => accumulator + current, 0);
}
// Example usage
const arr = [1, 2, 3, 4, 5];
console.log(sumArray(arr)); // Output: 15
How it works:
| Iteration | Accumulator | Current | Result |
|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
| 5 | 10 | 5 | 15 |
Method 2: Using for Loop
function sumArray(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
// Example usage
console.log(sumArray([10, 20, 30])); // Output: 60
Method 3: Using for...of Loop
function sumArray(numbers) {
let sum = 0;
for (const num of numbers) {
sum += num;
}
return sum;
}
// Example usage
console.log(sumArray([5, 10, 15])); // Output: 30
Method 4: Using forEach()
function sumArray(numbers) {
let sum = 0;
numbers.forEach(num => {
sum += num;
});
return sum;
}
// Example usage
console.log(sumArray([2, 4, 6, 8])); // Output: 20
Enhanced Version with Validation
function sumArray(numbers) {
// Check if input is a valid array
if (!Array.isArray(numbers)) {
throw new Error("Input must be an array");
}
// Filter only numbers and sum them
return numbers
.filter(item => typeof item === 'number' && !isNaN(item))
.reduce((sum, num) => sum + num, 0);
}
// Example usage
console.log(sumArray([1, 2, 'a', 3, null, 4])); // Output: 10
console.log(sumArray([])); // Output: 0
Comparison
| Method | Pros | Cons |
|---|
reduce() | Concise, functional | Less readable for beginners |
for loop | Fast, widely understood | More verbose |
for...of | Clean syntax | Slightly slower |
forEach() | Readable | Requires external variable |
Best Practice
The reduce() method is generally recommended because it's:
- ✅ Concise and clean
- ✅ Functional programming style
- ✅ Doesn't mutate external state
- ✅ Easy to chain with other array methods