javascriptbeginner10 minutes
Sum All Numbers in an Array Using JavaScript
Write a JavaScript function that takes an array of numbers and returns the sum of all the elements. This challenge helps you practice array iteration and basic function usage.
Challenge prompt
Create a function named sumArray that accepts a single argument — an array of numbers. Your function should calculate and return the sum of all numbers in the array. If the array is empty, return 0.
Guidance
- • Use a loop (for loop or forEach) to iterate over each element in the array.
- • Initialize a variable to hold the sum before the loop starts.
- • Add each number in the array to the sum variable inside the loop.
- • Return the total sum after processing all elements.
Hints
- • Consider using a for loop to iterate through the array elements.
- • Remember that the sum variable should start at zero before adding any numbers.
- • You can also explore the Array.reduce() method for a more concise solution.
Starter code
function sumArray(numbers) {
// Your code here
}Expected output
sumArray([1, 2, 3, 4]) returns 10 sumArray([]) returns 0 sumArray([10, -5, 7]) returns 12
Core concepts
arraysloopsfunctionsbasic arithmetic
Challenge a Friend
Send this duel to someone else and see if they can solve it.