Sum an array
JavaScript
Easy
Objective
Calculate the sum of the numbers in an array
Requirements
Create a function called
calculateSum
It should take a single argument, which is an array of numbers
It should return the sum of all the numbers in the array
The numbers in the array may be positive or negative
Check your solution
Tests
Function name is calculateSum | |||
calculateSum([1,2,3]) | Expected: | 6 | |
calculateSum([1,10,-2,6]) | Expected: | 15 |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function calculateSum(numbers) {
return numbers.reduce((sum, number) => sum + number, 0)
}
Click to reveal